DFace SDK  2.0.0
LTM
ArduinoJson-v5.13.3.h
1 // ArduinoJson - arduinojson.org
2 // Copyright Benoit Blanchon 2014-2018
3 // MIT License
4 
5 #pragma once
6 
7 #ifdef __cplusplus
8 
9 #define ARDUINOJSON_VERSION "5.13.3"
10 #define ARDUINOJSON_VERSION_MAJOR 5
11 #define ARDUINOJSON_VERSION_MINOR 13
12 #define ARDUINOJSON_VERSION_REVISION 3
13 #include <stddef.h> // for size_t
14 #include <stdint.h> // for uint8_t
15 #include <string.h>
16 namespace ArduinoJson {
17 namespace Internals {
18 class NonCopyable {
19  protected:
20  NonCopyable() {}
21  private:
22  NonCopyable(const NonCopyable&);
23  NonCopyable& operator=(const NonCopyable&);
24 };
25 }
26 }
27 #ifndef ARDUINOJSON_EMBEDDED_MODE
28 #if defined(ARDUINO) || defined(__IAR_SYSTEMS_ICC__) || defined(__XC) || \
29  defined(__ARMCC_VERSION)
30 #define ARDUINOJSON_EMBEDDED_MODE 1
31 #else
32 #define ARDUINOJSON_EMBEDDED_MODE 0
33 #endif
34 #endif
35 #if ARDUINOJSON_EMBEDDED_MODE
36 #ifndef ARDUINOJSON_USE_DOUBLE
37 #define ARDUINOJSON_USE_DOUBLE 0
38 #endif
39 #ifndef ARDUINOJSON_USE_LONG_LONG
40 #define ARDUINOJSON_USE_LONG_LONG 0
41 #endif
42 #ifndef ARDUINOJSON_USE_INT64
43 #define ARDUINOJSON_USE_INT64 0
44 #endif
45 #ifndef ARDUINOJSON_ENABLE_STD_STRING
46 #define ARDUINOJSON_ENABLE_STD_STRING 0
47 #endif
48 #ifndef ARDUINOJSON_ENABLE_STD_STREAM
49 #define ARDUINOJSON_ENABLE_STD_STREAM 0
50 #endif
51 #ifndef ARDUINOJSON_DEFAULT_NESTING_LIMIT
52 #define ARDUINOJSON_DEFAULT_NESTING_LIMIT 10
53 #endif
54 #else // ARDUINOJSON_EMBEDDED_MODE
55 #ifndef ARDUINOJSON_USE_DOUBLE
56 #define ARDUINOJSON_USE_DOUBLE 1
57 #endif
58 #ifndef ARDUINOJSON_USE_LONG_LONG
59 #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)
60 #define ARDUINOJSON_USE_LONG_LONG 1
61 #else
62 #define ARDUINOJSON_USE_LONG_LONG 0
63 #endif
64 #endif
65 #ifndef ARDUINOJSON_USE_INT64
66 #if defined(_MSC_VER) && _MSC_VER <= 1700
67 #define ARDUINOJSON_USE_INT64 1
68 #else
69 #define ARDUINOJSON_USE_INT64 0
70 #endif
71 #endif
72 #ifndef ARDUINOJSON_ENABLE_STD_STRING
73 #define ARDUINOJSON_ENABLE_STD_STRING 1
74 #endif
75 #ifndef ARDUINOJSON_ENABLE_STD_STREAM
76 #define ARDUINOJSON_ENABLE_STD_STREAM 1
77 #endif
78 #ifndef ARDUINOJSON_DEFAULT_NESTING_LIMIT
79 #define ARDUINOJSON_DEFAULT_NESTING_LIMIT 50
80 #endif
81 #endif // ARDUINOJSON_EMBEDDED_MODE
82 #ifdef ARDUINO
83 #ifndef ARDUINOJSON_ENABLE_ARDUINO_STRING
84 #define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
85 #endif
86 #ifndef ARDUINOJSON_ENABLE_ARDUINO_STREAM
87 #define ARDUINOJSON_ENABLE_ARDUINO_STREAM 1
88 #endif
89 #else // ARDUINO
90 #ifndef ARDUINOJSON_ENABLE_ARDUINO_STRING
91 #define ARDUINOJSON_ENABLE_ARDUINO_STRING 0
92 #endif
93 #ifndef ARDUINOJSON_ENABLE_ARDUINO_STREAM
94 #define ARDUINOJSON_ENABLE_ARDUINO_STREAM 0
95 #endif
96 #endif // ARDUINO
97 #ifndef ARDUINOJSON_ENABLE_PROGMEM
98 #ifdef PROGMEM
99 #define ARDUINOJSON_ENABLE_PROGMEM 1
100 #else
101 #define ARDUINOJSON_ENABLE_PROGMEM 0
102 #endif
103 #endif
104 #ifndef ARDUINOJSON_ENABLE_ALIGNMENT
105 #ifdef ARDUINO_ARCH_AVR
106 #define ARDUINOJSON_ENABLE_ALIGNMENT 0
107 #else
108 #define ARDUINOJSON_ENABLE_ALIGNMENT 1
109 #endif
110 #endif
111 #ifndef ARDUINOJSON_ENABLE_DEPRECATED
112 #define ARDUINOJSON_ENABLE_DEPRECATED 1
113 #endif
114 #ifndef ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD
115 #define ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD 1e7
116 #endif
117 #ifndef ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD
118 #define ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD 1e-5
119 #endif
120 #if ARDUINOJSON_USE_LONG_LONG && ARDUINOJSON_USE_INT64
121 #error ARDUINOJSON_USE_LONG_LONG and ARDUINOJSON_USE_INT64 cannot be set together
122 #endif
123 namespace ArduinoJson {
124 namespace Internals {
125 #if ARDUINOJSON_USE_DOUBLE
126 typedef double JsonFloat;
127 #else
128 typedef float JsonFloat;
129 #endif
130 }
131 }
132 namespace ArduinoJson {
133 namespace Internals {
134 #if ARDUINOJSON_USE_LONG_LONG
135 typedef long long JsonInteger;
136 typedef unsigned long long JsonUInt;
137 #elif ARDUINOJSON_USE_INT64
138 typedef __int64 JsonInteger;
139 typedef unsigned _int64 JsonUInt;
140 #else
141 typedef long JsonInteger;
142 typedef unsigned long JsonUInt;
143 #endif
144 }
145 }
146 namespace ArduinoJson {
147 class JsonArray;
148 class JsonObject;
149 namespace Internals {
150 union JsonVariantContent {
151  JsonFloat asFloat; // used for double and float
152  JsonUInt asInteger; // used for bool, char, short, int and longs
153  const char* asString; // asString can be null
154  JsonArray* asArray; // asArray cannot be null
155  JsonObject* asObject; // asObject cannot be null
156 };
157 }
158 }
159 namespace ArduinoJson {
160 namespace Internals {
161 template <typename T>
162 struct JsonVariantDefault {
163  static T get() {
164  return T();
165  }
166 };
167 template <typename T>
168 struct JsonVariantDefault<const T> : JsonVariantDefault<T> {};
169 template <typename T>
170 struct JsonVariantDefault<T&> : JsonVariantDefault<T> {};
171 }
172 }
173 namespace ArduinoJson {
174 class JsonArray;
175 class JsonObject;
176 namespace Internals {
177 enum JsonVariantType {
178  JSON_UNDEFINED, // JsonVariant has not been initialized
179  JSON_UNPARSED, // JsonVariant contains an unparsed string
180  JSON_STRING, // JsonVariant stores a const char*
181  JSON_BOOLEAN, // JsonVariant stores a bool
182  JSON_POSITIVE_INTEGER, // JsonVariant stores an JsonUInt
183  JSON_NEGATIVE_INTEGER, // JsonVariant stores an JsonUInt that must be negated
184  JSON_ARRAY, // JsonVariant stores a pointer to a JsonArray
185  JSON_OBJECT, // JsonVariant stores a pointer to a JsonObject
186  JSON_FLOAT // JsonVariant stores a JsonFloat
187 };
188 }
189 }
190 namespace ArduinoJson {
191 namespace Internals {
192 template <typename T>
193 struct JsonVariantAs {
194  typedef T type;
195 };
196 template <>
197 struct JsonVariantAs<char*> {
198  typedef const char* type;
199 };
200 template <>
201 struct JsonVariantAs<JsonArray> {
202  typedef JsonArray& type;
203 };
204 template <>
205 struct JsonVariantAs<const JsonArray> {
206  typedef const JsonArray& type;
207 };
208 template <>
209 struct JsonVariantAs<JsonObject> {
210  typedef JsonObject& type;
211 };
212 template <>
213 struct JsonVariantAs<const JsonObject> {
214  typedef const JsonObject& type;
215 };
216 }
217 }
218 #ifdef _MSC_VER // Visual Studio
219 #define FORCE_INLINE // __forceinline causes C4714 when returning std::string
220 #define NO_INLINE __declspec(noinline)
221 #define DEPRECATED(msg) __declspec(deprecated(msg))
222 #elif defined(__GNUC__) // GCC or Clang
223 #define FORCE_INLINE __attribute__((always_inline))
224 #define NO_INLINE __attribute__((noinline))
225 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
226 #define DEPRECATED(msg) __attribute__((deprecated(msg)))
227 #else
228 #define DEPRECATED(msg) __attribute__((deprecated))
229 #endif
230 #else // Other compilers
231 #define FORCE_INLINE
232 #define NO_INLINE
233 #define DEPRECATED(msg)
234 #endif
235 namespace ArduinoJson {
236 namespace Internals {
237 template <typename TImpl>
238 class JsonVariantCasts {
239  public:
240 #if ARDUINOJSON_ENABLE_DEPRECATED
241  DEPRECATED("use as<JsonArray>() instead")
242  FORCE_INLINE JsonArray &asArray() const {
243  return impl()->template as<JsonArray>();
244  }
245  DEPRECATED("use as<JsonObject>() instead")
246  FORCE_INLINE JsonObject &asObject() const {
247  return impl()->template as<JsonObject>();
248  }
249  DEPRECATED("use as<char*>() instead")
250  FORCE_INLINE const char *asString() const {
251  return impl()->template as<const char *>();
252  }
253 #endif
254  FORCE_INLINE operator JsonArray &() const {
255  return impl()->template as<JsonArray &>();
256  }
257  FORCE_INLINE operator JsonObject &() const {
258  return impl()->template as<JsonObject &>();
259  }
260  template <typename T>
261  FORCE_INLINE operator T() const {
262  return impl()->template as<T>();
263  }
264  private:
265  const TImpl *impl() const {
266  return static_cast<const TImpl *>(this);
267  }
268 };
269 }
270 }
271 namespace ArduinoJson {
272 namespace Internals {
273 template <bool Condition, typename T = void>
274 struct EnableIf {};
275 template <typename T>
276 struct EnableIf<true, T> {
277  typedef T type;
278 };
279 }
280 }
281 namespace ArduinoJson {
282 namespace Internals {
283 template <typename TBase, typename TDerived>
284 class IsBaseOf {
285  protected: // <- to avoid GCC's "all member functions in class are private"
286  typedef char Yes[1];
287  typedef char No[2];
288  static Yes &probe(const TBase *);
289  static No &probe(...);
290  public:
291  enum {
292  value = sizeof(probe(reinterpret_cast<TDerived *>(0))) == sizeof(Yes)
293  };
294 };
295 }
296 }
297 namespace ArduinoJson {
298 namespace Internals {
299 template <typename T, typename U>
300 struct IsSame {
301  static const bool value = false;
302 };
303 template <typename T>
304 struct IsSame<T, T> {
305  static const bool value = true;
306 };
307 }
308 }
309 namespace ArduinoJson {
310 namespace Internals {
311 template <typename T>
312 struct IsChar {
313  static const bool value = IsSame<T, char>::value ||
314  IsSame<T, signed char>::value ||
315  IsSame<T, unsigned char>::value;
316 };
317 template <typename T>
318 struct IsChar<const T> : IsChar<T> {};
319 }
320 }
321 namespace ArduinoJson {
322 namespace Internals {
323 template <typename T>
324 struct IsConst {
325  static const bool value = false;
326 };
327 template <typename T>
328 struct IsConst<const T> {
329  static const bool value = true;
330 };
331 }
332 }
333 namespace ArduinoJson {
334 namespace Internals {
335 template <typename T>
336 struct RemoveReference {
337  typedef T type;
338 };
339 template <typename T>
340 struct RemoveReference<T&> {
341  typedef T type;
342 };
343 }
344 }
345 namespace ArduinoJson {
346 namespace Internals {
347 template <typename TString, typename Enable = void>
348 struct StringTraits {
349  static const bool has_append = false;
350  static const bool has_equals = false;
351 };
352 template <typename TString>
353 struct StringTraits<const TString, void> : StringTraits<TString> {};
354 template <typename TString>
355 struct StringTraits<TString&, void> : StringTraits<TString> {};
356 }
357 }
358 #if ARDUINOJSON_ENABLE_ARDUINO_STREAM
359 #include <Stream.h>
360 namespace ArduinoJson {
361 namespace Internals {
362 struct ArduinoStreamTraits {
363  class Reader {
364  Stream& _stream;
365  char _current, _next;
366  public:
367  Reader(Stream& stream) : _stream(stream), _current(0), _next(0) {}
368  void move() {
369  _current = _next;
370  _next = 0;
371  }
372  char current() {
373  if (!_current) _current = read();
374  return _current;
375  }
376  char next() {
377  if (!_next) _next = read();
378  return _next;
379  }
380  private:
381  char read() {
382  char c = 0;
383  _stream.readBytes(&c, 1);
384  return c;
385  }
386  };
387  static const bool has_append = false;
388  static const bool has_equals = false;
389 };
390 template <typename TStream>
391 struct StringTraits<
392  TStream,
393  typename EnableIf<
394  IsBaseOf<Stream, typename RemoveReference<TStream>::type>::value>::type>
395  : ArduinoStreamTraits {};
396 }
397 }
398 #endif
399 namespace ArduinoJson {
400 namespace Internals {
401 template <typename TChar>
402 struct CharPointerTraits {
403  class Reader {
404  const TChar* _ptr;
405  public:
406  Reader(const TChar* ptr)
407  : _ptr(ptr ? ptr : reinterpret_cast<const TChar*>("")) {}
408  void move() {
409  ++_ptr;
410  }
411  char current() const {
412  return char(_ptr[0]);
413  }
414  char next() const {
415  return char(_ptr[1]);
416  }
417  };
418  static bool equals(const TChar* str, const char* expected) {
419  const char* actual = reinterpret_cast<const char*>(str);
420  if (!actual || !expected) return actual == expected;
421  return strcmp(actual, expected) == 0;
422  }
423  static bool is_null(const TChar* str) {
424  return !str;
425  }
426  typedef const char* duplicate_t;
427  template <typename Buffer>
428  static duplicate_t duplicate(const TChar* str, Buffer* buffer) {
429  if (!str) return NULL;
430  size_t size = strlen(reinterpret_cast<const char*>(str)) + 1;
431  void* dup = buffer->alloc(size);
432  if (dup != NULL) memcpy(dup, str, size);
433  return static_cast<duplicate_t>(dup);
434  }
435  static const bool has_append = false;
436  static const bool has_equals = true;
437  static const bool should_duplicate = !IsConst<TChar>::value;
438 };
439 template <typename TChar>
440 struct StringTraits<TChar*, typename EnableIf<IsChar<TChar>::value>::type>
441  : CharPointerTraits<TChar> {};
442 } // namespace Internals
443 } // namespace ArduinoJson
444 #if ARDUINOJSON_ENABLE_PROGMEM
445 namespace ArduinoJson {
446 namespace Internals {
447 template <>
448 struct StringTraits<const __FlashStringHelper*, void> {
449  class Reader {
450  const char* _ptr;
451  public:
452  Reader(const __FlashStringHelper* ptr)
453  : _ptr(reinterpret_cast<const char*>(ptr)) {}
454  void move() {
455  _ptr++;
456  }
457  char current() const {
458  return pgm_read_byte_near(_ptr);
459  }
460  char next() const {
461  return pgm_read_byte_near(_ptr + 1);
462  }
463  };
464  static bool equals(const __FlashStringHelper* str, const char* expected) {
465  const char* actual = reinterpret_cast<const char*>(str);
466  if (!actual || !expected) return actual == expected;
467  return strcmp_P(expected, actual) == 0;
468  }
469  static bool is_null(const __FlashStringHelper* str) {
470  return !str;
471  }
472  typedef const char* duplicate_t;
473  template <typename Buffer>
474  static duplicate_t duplicate(const __FlashStringHelper* str, Buffer* buffer) {
475  if (!str) return NULL;
476  size_t size = strlen_P((const char*)str) + 1;
477  void* dup = buffer->alloc(size);
478  if (dup != NULL) memcpy_P(dup, (const char*)str, size);
479  return static_cast<duplicate_t>(dup);
480  }
481  static const bool has_append = false;
482  static const bool has_equals = true;
483  static const bool should_duplicate = true;
484 };
485 } // namespace Internals
486 } // namespace ArduinoJson
487 #endif
488 #if ARDUINOJSON_ENABLE_STD_STREAM
489 #include <istream>
490 namespace ArduinoJson {
491 namespace Internals {
492 struct StdStreamTraits {
493  class Reader {
494  std::istream& _stream;
495  char _current, _next;
496  public:
497  Reader(std::istream& stream) : _stream(stream), _current(0), _next(0) {}
498  void move() {
499  _current = _next;
500  _next = 0;
501  }
502  char current() {
503  if (!_current) _current = read();
504  return _current;
505  }
506  char next() {
507  if (!_next) _next = read();
508  return _next;
509  }
510  private:
511  Reader& operator=(const Reader&); // Visual Studio C4512
512  char read() {
513  return _stream.eof() ? '\0' : static_cast<char>(_stream.get());
514  }
515  };
516  static const bool has_append = false;
517  static const bool has_equals = false;
518 };
519 template <typename TStream>
520 struct StringTraits<
521  TStream,
522  typename EnableIf<IsBaseOf<
523  std::istream, typename RemoveReference<TStream>::type>::value>::type>
524  : StdStreamTraits {};
525 }
526 }
527 #endif
528 #if ARDUINOJSON_ENABLE_STD_STRING || ARDUINOJSON_ENABLE_ARDUINO_STRING
529 #if ARDUINOJSON_ENABLE_ARDUINO_STRING
530 #include <WString.h>
531 #endif
532 #if ARDUINOJSON_ENABLE_STD_STRING
533 #include <string>
534 #endif
535 namespace ArduinoJson {
536 namespace Internals {
537 template <typename TString>
538 struct StdStringTraits {
539  typedef const char* duplicate_t;
540  template <typename Buffer>
541  static duplicate_t duplicate(const TString& str, Buffer* buffer) {
542  if (!str.c_str()) return NULL; // <- Arduino string can return NULL
543  size_t size = str.length() + 1;
544  void* dup = buffer->alloc(size);
545  if (dup != NULL) memcpy(dup, str.c_str(), size);
546  return static_cast<duplicate_t>(dup);
547  }
548  static bool is_null(const TString& str) {
549  return !str.c_str();
550  }
551  struct Reader : CharPointerTraits<char>::Reader {
552  Reader(const TString& str) : CharPointerTraits<char>::Reader(str.c_str()) {}
553  };
554  static bool equals(const TString& str, const char* expected) {
555  const char* actual = str.c_str();
556  if (!actual || !expected) return actual == expected;
557  return 0 == strcmp(actual, expected);
558  }
559  static void append(TString& str, char c) {
560  str += c;
561  }
562  static void append(TString& str, const char* s) {
563  str += s;
564  }
565  static const bool has_append = true;
566  static const bool has_equals = true;
567  static const bool should_duplicate = true;
568 };
569 #if ARDUINOJSON_ENABLE_ARDUINO_STRING
570 template <>
571 struct StringTraits<String, void> : StdStringTraits<String> {};
572 template <>
573 struct StringTraits<StringSumHelper, void> : StdStringTraits<StringSumHelper> {
574 };
575 #endif
576 #if ARDUINOJSON_ENABLE_STD_STRING
577 template <>
578 struct StringTraits<std::string, void> : StdStringTraits<std::string> {};
579 #endif
580 } // namespace Internals
581 } // namespace ArduinoJson
582 #endif
583 namespace ArduinoJson {
584 namespace Internals {
585 class JsonVariantTag {};
586 template <typename T>
587 struct IsVariant : IsBaseOf<JsonVariantTag, T> {};
588 }
589 }
590 namespace ArduinoJson {
591 namespace Internals {
592 template <typename TImpl>
593 class JsonVariantComparisons {
594  public:
595  template <typename TComparand>
596  friend bool operator==(const JsonVariantComparisons &variant,
597  TComparand comparand) {
598  return variant.equals(comparand);
599  }
600  template <typename TComparand>
601  friend typename EnableIf<!IsVariant<TComparand>::value, bool>::type
602  operator==(TComparand comparand, const JsonVariantComparisons &variant) {
603  return variant.equals(comparand);
604  }
605  template <typename TComparand>
606  friend bool operator!=(const JsonVariantComparisons &variant,
607  TComparand comparand) {
608  return !variant.equals(comparand);
609  }
610  template <typename TComparand>
611  friend typename EnableIf<!IsVariant<TComparand>::value, bool>::type
612  operator!=(TComparand comparand, const JsonVariantComparisons &variant) {
613  return !variant.equals(comparand);
614  }
615  template <typename TComparand>
616  friend bool operator<=(const JsonVariantComparisons &left, TComparand right) {
617  return left.as<TComparand>() <= right;
618  }
619  template <typename TComparand>
620  friend bool operator<=(TComparand comparand,
621  const JsonVariantComparisons &variant) {
622  return comparand <= variant.as<TComparand>();
623  }
624  template <typename TComparand>
625  friend bool operator>=(const JsonVariantComparisons &variant,
626  TComparand comparand) {
627  return variant.as<TComparand>() >= comparand;
628  }
629  template <typename TComparand>
630  friend bool operator>=(TComparand comparand,
631  const JsonVariantComparisons &variant) {
632  return comparand >= variant.as<TComparand>();
633  }
634  template <typename TComparand>
635  friend bool operator<(const JsonVariantComparisons &varian,
636  TComparand comparand) {
637  return varian.as<TComparand>() < comparand;
638  }
639  template <typename TComparand>
640  friend bool operator<(TComparand comparand,
641  const JsonVariantComparisons &variant) {
642  return comparand < variant.as<TComparand>();
643  }
644  template <typename TComparand>
645  friend bool operator>(const JsonVariantComparisons &variant,
646  TComparand comparand) {
647  return variant.as<TComparand>() > comparand;
648  }
649  template <typename TComparand>
650  friend bool operator>(TComparand comparand,
651  const JsonVariantComparisons &variant) {
652  return comparand > variant.as<TComparand>();
653  }
654  private:
655  const TImpl *impl() const {
656  return static_cast<const TImpl *>(this);
657  }
658  template <typename T>
659  const typename JsonVariantAs<T>::type as() const {
660  return impl()->template as<T>();
661  }
662  template <typename T>
663  bool is() const {
664  return impl()->template is<T>();
665  }
666  template <typename TString>
667  typename EnableIf<StringTraits<TString>::has_equals, bool>::type equals(
668  const TString &comparand) const {
669  const char *value = as<const char *>();
670  return StringTraits<TString>::equals(comparand, value);
671  }
672  template <typename TComparand>
673  typename EnableIf<!IsVariant<TComparand>::value &&
674  !StringTraits<TComparand>::has_equals,
675  bool>::type
676  equals(const TComparand &comparand) const {
677  return as<TComparand>() == comparand;
678  }
679  template <typename TVariant2>
680  bool equals(const JsonVariantComparisons<TVariant2> &right) const {
681  using namespace Internals;
682  if (is<bool>() && right.template is<bool>())
683  return as<bool>() == right.template as<bool>();
684  if (is<JsonInteger>() && right.template is<JsonInteger>())
685  return as<JsonInteger>() == right.template as<JsonInteger>();
686  if (is<JsonFloat>() && right.template is<JsonFloat>())
687  return as<JsonFloat>() == right.template as<JsonFloat>();
688  if (is<JsonArray>() && right.template is<JsonArray>())
689  return as<JsonArray>() == right.template as<JsonArray>();
690  if (is<JsonObject>() && right.template is<JsonObject>())
691  return as<JsonObject>() == right.template as<JsonObject>();
692  if (is<char *>() && right.template is<char *>())
693  return StringTraits<const char *>::equals(as<char *>(),
694  right.template as<char *>());
695  return false;
696  }
697 };
698 } // namespace Internals
699 } // namespace ArduinoJson
700 namespace ArduinoJson {
701 namespace Internals {
702 template <typename T>
703 struct IsSignedIntegral {
704  static const bool value =
705  IsSame<T, signed char>::value || IsSame<T, signed short>::value ||
706  IsSame<T, signed int>::value || IsSame<T, signed long>::value ||
707 #if ARDUINOJSON_USE_LONG_LONG
708  IsSame<T, signed long long>::value ||
709 #endif
710 #if ARDUINOJSON_USE_INT64
711  IsSame<T, signed __int64>::value ||
712 #endif
713  false;
714 };
715 }
716 }
717 namespace ArduinoJson {
718 namespace Internals {
719 template <typename T>
720 struct IsUnsignedIntegral {
721  static const bool value =
722  IsSame<T, unsigned char>::value || IsSame<T, unsigned short>::value ||
723  IsSame<T, unsigned int>::value || IsSame<T, unsigned long>::value ||
724 #if ARDUINOJSON_USE_LONG_LONG
725  IsSame<T, unsigned long long>::value ||
726 #endif
727 #if ARDUINOJSON_USE_INT64
728  IsSame<T, unsigned __int64>::value ||
729 #endif
730  false;
731 };
732 }
733 }
734 namespace ArduinoJson {
735 namespace Internals {
736 template <typename T>
737 struct IsIntegral {
738  static const bool value = IsSignedIntegral<T>::value ||
739  IsUnsignedIntegral<T>::value ||
740  IsSame<T, char>::value;
741 };
742 template <typename T>
743 struct IsIntegral<const T> : IsIntegral<T> {};
744 }
745 }
746 namespace ArduinoJson {
747 namespace Internals {
748 template <typename TImpl>
749 class JsonVariantOr {
750  public:
751  template <typename T>
752  typename EnableIf<!IsIntegral<T>::value, T>::type operator|(
753  const T &defaultValue) const {
754  if (impl()->template is<T>())
755  return impl()->template as<T>();
756  else
757  return defaultValue;
758  }
759  const char *operator|(const char *defaultValue) const {
760  const char *value = impl()->template as<const char *>();
761  return value ? value : defaultValue;
762  }
763  template <typename Integer>
764  typename EnableIf<IsIntegral<Integer>::value, Integer>::type operator|(
765  const Integer &defaultValue) const {
766  if (impl()->template is<double>())
767  return impl()->template as<Integer>();
768  else
769  return defaultValue;
770  }
771  private:
772  const TImpl *impl() const {
773  return static_cast<const TImpl *>(this);
774  }
775 };
776 } // namespace Internals
777 } // namespace ArduinoJson
778 namespace ArduinoJson {
779 namespace Internals {
780 class JsonArraySubscript;
781 template <typename TKey>
782 class JsonObjectSubscript;
783 template <typename TImpl>
784 class JsonVariantSubscripts {
785  public:
786  size_t size() const {
787  return impl()->template as<JsonArray>().size() +
788  impl()->template as<JsonObject>().size();
789  }
790  FORCE_INLINE const JsonArraySubscript operator[](size_t index) const;
791  FORCE_INLINE JsonArraySubscript operator[](size_t index);
792  template <typename TString>
793  FORCE_INLINE
794  typename EnableIf<StringTraits<TString>::has_equals,
795  const JsonObjectSubscript<const TString &> >::type
796  operator[](const TString &key) const {
797  return impl()->template as<JsonObject>()[key];
798  }
799  template <typename TString>
800  FORCE_INLINE typename EnableIf<StringTraits<TString>::has_equals,
801  JsonObjectSubscript<const TString &> >::type
802  operator[](const TString &key) {
803  return impl()->template as<JsonObject>()[key];
804  }
805  template <typename TString>
806  FORCE_INLINE typename EnableIf<StringTraits<const TString *>::has_equals,
807  JsonObjectSubscript<const TString *> >::type
808  operator[](const TString *key) {
809  return impl()->template as<JsonObject>()[key];
810  }
811  template <typename TString>
812  FORCE_INLINE
813  typename EnableIf<StringTraits<TString *>::has_equals,
814  const JsonObjectSubscript<const TString *> >::type
815  operator[](const TString *key) const {
816  return impl()->template as<JsonObject>()[key];
817  }
818  private:
819  const TImpl *impl() const {
820  return static_cast<const TImpl *>(this);
821  }
822 };
823 }
824 }
825 namespace ArduinoJson {
826 namespace Internals {
827 class DummyPrint {
828  public:
829  size_t print(char) {
830  return 1;
831  }
832  size_t print(const char* s) {
833  return strlen(s);
834  }
835 };
836 }
837 }
838 namespace ArduinoJson {
839 namespace Internals {
840 template <typename TString>
841 class DynamicStringBuilder {
842  public:
843  DynamicStringBuilder(TString &str) : _str(str) {}
844  size_t print(char c) {
845  StringTraits<TString>::append(_str, c);
846  return 1;
847  }
848  size_t print(const char *s) {
849  size_t initialLen = _str.length();
850  StringTraits<TString>::append(_str, s);
851  return _str.length() - initialLen;
852  }
853  private:
854  DynamicStringBuilder &operator=(const DynamicStringBuilder &);
855  TString &_str;
856 };
857 }
858 }
859 namespace ArduinoJson {
860 namespace Internals {
861 template <typename Print>
862 class IndentedPrint {
863  public:
864  explicit IndentedPrint(Print &p) : sink(&p) {
865  level = 0;
866  tabSize = 2;
867  isNewLine = true;
868  }
869  size_t print(char c) {
870  size_t n = 0;
871  if (isNewLine) n += writeTabs();
872  n += sink->print(c);
873  isNewLine = c == '\n';
874  return n;
875  }
876  size_t print(const char *s) {
877  size_t n = 0;
878  while (*s) n += print(*s++);
879  return n;
880  }
881  void indent() {
882  if (level < MAX_LEVEL) level++;
883  }
884  void unindent() {
885  if (level > 0) level--;
886  }
887  void setTabSize(uint8_t n) {
888  if (n < MAX_TAB_SIZE) tabSize = n & MAX_TAB_SIZE;
889  }
890  private:
891  Print *sink;
892  uint8_t level : 4;
893  uint8_t tabSize : 3;
894  bool isNewLine : 1;
895  size_t writeTabs() {
896  size_t n = 0;
897  for (int i = 0; i < level * tabSize; i++) n += sink->print(' ');
898  return n;
899  }
900  static const int MAX_LEVEL = 15; // because it's only 4 bits
901  static const int MAX_TAB_SIZE = 7; // because it's only 3 bits
902 };
903 }
904 }
905 namespace ArduinoJson {
906 namespace Internals {
907 class Encoding {
908  public:
909  static char escapeChar(char c) {
910  const char *p = escapeTable(false);
911  while (p[0] && p[1] != c) {
912  p += 2;
913  }
914  return p[0];
915  }
916  static char unescapeChar(char c) {
917  const char *p = escapeTable(true);
918  for (;;) {
919  if (p[0] == '\0') return c;
920  if (p[0] == c) return p[1];
921  p += 2;
922  }
923  }
924  private:
925  static const char *escapeTable(bool excludeIdenticals) {
926  return &"\"\"\\\\b\bf\fn\nr\rt\t"[excludeIdenticals ? 4 : 0];
927  }
928 };
929 }
930 }
931 namespace ArduinoJson {
932 namespace Internals {
933 template <typename T>
934 bool isNaN(T x) {
935  return x != x;
936 }
937 template <typename T>
938 bool isInfinity(T x) {
939  return x != 0.0 && x * 2 == x;
940 }
941 }
942 }
943 #include <stdlib.h> // for size_t
944 namespace ArduinoJson {
945 namespace Internals {
946 template <typename T, size_t = sizeof(T)>
947 struct FloatTraits {};
948 template <typename T>
949 struct FloatTraits<T, 8 /*64bits*/> {
950  typedef int64_t mantissa_type;
951  static const short mantissa_bits = 52;
952  static const mantissa_type mantissa_max =
953  (static_cast<mantissa_type>(1) << mantissa_bits) - 1;
954  typedef int16_t exponent_type;
955  static const exponent_type exponent_max = 308;
956  template <typename TExponent>
957  static T make_float(T m, TExponent e) {
958  if (e > 0) {
959  for (uint8_t index = 0; e != 0; index++) {
960  if (e & 1) m *= positiveBinaryPowerOfTen(index);
961  e >>= 1;
962  }
963  } else {
964  e = TExponent(-e);
965  for (uint8_t index = 0; e != 0; index++) {
966  if (e & 1) m *= negativeBinaryPowerOfTen(index);
967  e >>= 1;
968  }
969  }
970  return m;
971  }
972  static T positiveBinaryPowerOfTen(int index) {
973  static T factors[] = {
974  1e1,
975  1e2,
976  1e4,
977  1e8,
978  1e16,
979  forge(0x4693B8B5, 0xB5056E17), // 1e32
980  forge(0x4D384F03, 0xE93FF9F5), // 1e64
981  forge(0x5A827748, 0xF9301D32), // 1e128
982  forge(0x75154FDD, 0x7F73BF3C) // 1e256
983  };
984  return factors[index];
985  }
986  static T negativeBinaryPowerOfTen(int index) {
987  static T factors[] = {
988  forge(0x3FB99999, 0x9999999A), // 1e-1
989  forge(0x3F847AE1, 0x47AE147B), // 1e-2
990  forge(0x3F1A36E2, 0xEB1C432D), // 1e-4
991  forge(0x3E45798E, 0xE2308C3A), // 1e-8
992  forge(0x3C9CD2B2, 0x97D889BC), // 1e-16
993  forge(0x3949F623, 0xD5A8A733), // 1e-32
994  forge(0x32A50FFD, 0x44F4A73D), // 1e-64
995  forge(0x255BBA08, 0xCF8C979D), // 1e-128
996  forge(0x0AC80628, 0x64AC6F43) // 1e-256
997  };
998  return factors[index];
999  }
1000  static T negativeBinaryPowerOfTenPlusOne(int index) {
1001  static T factors[] = {
1002  1e0,
1003  forge(0x3FB99999, 0x9999999A), // 1e-1
1004  forge(0x3F50624D, 0xD2F1A9FC), // 1e-3
1005  forge(0x3E7AD7F2, 0x9ABCAF48), // 1e-7
1006  forge(0x3CD203AF, 0x9EE75616), // 1e-15
1007  forge(0x398039D6, 0x65896880), // 1e-31
1008  forge(0x32DA53FC, 0x9631D10D), // 1e-63
1009  forge(0x25915445, 0x81B7DEC2), // 1e-127
1010  forge(0x0AFE07B2, 0x7DD78B14) // 1e-255
1011  };
1012  return factors[index];
1013  }
1014  static T nan() {
1015  return forge(0x7ff80000, 0x00000000);
1016  }
1017  static T inf() {
1018  return forge(0x7ff00000, 0x00000000);
1019  }
1020  static T forge(uint32_t msb, uint32_t lsb) {
1021  union {
1022  uint64_t integerBits;
1023  T floatBits;
1024  };
1025  integerBits = (uint64_t(msb) << 32) | lsb;
1026  return floatBits;
1027  }
1028 };
1029 template <typename T>
1030 struct FloatTraits<T, 4 /*32bits*/> {
1031  typedef int32_t mantissa_type;
1032  static const short mantissa_bits = 23;
1033  static const mantissa_type mantissa_max =
1034  (static_cast<mantissa_type>(1) << mantissa_bits) - 1;
1035  typedef int8_t exponent_type;
1036  static const exponent_type exponent_max = 38;
1037  template <typename TExponent>
1038  static T make_float(T m, TExponent e) {
1039  if (e > 0) {
1040  for (uint8_t index = 0; e != 0; index++) {
1041  if (e & 1) m *= positiveBinaryPowerOfTen(index);
1042  e >>= 1;
1043  }
1044  } else {
1045  e = -e;
1046  for (uint8_t index = 0; e != 0; index++) {
1047  if (e & 1) m *= negativeBinaryPowerOfTen(index);
1048  e >>= 1;
1049  }
1050  }
1051  return m;
1052  }
1053  static T positiveBinaryPowerOfTen(int index) {
1054  static T factors[] = {1e1f, 1e2f, 1e4f, 1e8f, 1e16f, 1e32f};
1055  return factors[index];
1056  }
1057  static T negativeBinaryPowerOfTen(int index) {
1058  static T factors[] = {1e-1f, 1e-2f, 1e-4f, 1e-8f, 1e-16f, 1e-32f};
1059  return factors[index];
1060  }
1061  static T negativeBinaryPowerOfTenPlusOne(int index) {
1062  static T factors[] = {1e0f, 1e-1f, 1e-3f, 1e-7f, 1e-15f, 1e-31f};
1063  return factors[index];
1064  }
1065  static T forge(uint32_t bits) {
1066  union {
1067  uint32_t integerBits;
1068  T floatBits;
1069  };
1070  integerBits = bits;
1071  return floatBits;
1072  }
1073  static T nan() {
1074  return forge(0x7fc00000);
1075  }
1076  static T inf() {
1077  return forge(0x7f800000);
1078  }
1079 };
1080 }
1081 }
1082 namespace ArduinoJson {
1083 namespace Internals {
1084 template <typename TFloat>
1085 struct FloatParts {
1086  uint32_t integral;
1087  uint32_t decimal;
1088  int16_t exponent;
1089  int8_t decimalPlaces;
1090  FloatParts(TFloat value) {
1091  uint32_t maxDecimalPart = sizeof(TFloat) >= 8 ? 1000000000 : 1000000;
1092  decimalPlaces = sizeof(TFloat) >= 8 ? 9 : 6;
1093  exponent = normalize(value);
1094  integral = uint32_t(value);
1095  for (uint32_t tmp = integral; tmp >= 10; tmp /= 10) {
1096  maxDecimalPart /= 10;
1097  decimalPlaces--;
1098  }
1099  TFloat remainder = (value - TFloat(integral)) * TFloat(maxDecimalPart);
1100  decimal = uint32_t(remainder);
1101  remainder = remainder - TFloat(decimal);
1102  decimal += uint32_t(remainder * 2);
1103  if (decimal >= maxDecimalPart) {
1104  decimal = 0;
1105  integral++;
1106  if (exponent && integral >= 10) {
1107  exponent++;
1108  integral = 1;
1109  }
1110  }
1111  while (decimal % 10 == 0 && decimalPlaces > 0) {
1112  decimal /= 10;
1113  decimalPlaces--;
1114  }
1115  }
1116  static int16_t normalize(TFloat& value) {
1117  typedef FloatTraits<TFloat> traits;
1118  int16_t powersOf10 = 0;
1119  int8_t index = sizeof(TFloat) == 8 ? 8 : 5;
1120  int bit = 1 << index;
1121  if (value >= ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD) {
1122  for (; index >= 0; index--) {
1123  if (value >= traits::positiveBinaryPowerOfTen(index)) {
1124  value *= traits::negativeBinaryPowerOfTen(index);
1125  powersOf10 = int16_t(powersOf10 + bit);
1126  }
1127  bit >>= 1;
1128  }
1129  }
1130  if (value > 0 && value <= ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD) {
1131  for (; index >= 0; index--) {
1132  if (value < traits::negativeBinaryPowerOfTenPlusOne(index)) {
1133  value *= traits::positiveBinaryPowerOfTen(index);
1134  powersOf10 = int16_t(powersOf10 - bit);
1135  }
1136  bit >>= 1;
1137  }
1138  }
1139  return powersOf10;
1140  }
1141 };
1142 }
1143 }
1144 namespace ArduinoJson {
1145 namespace Internals {
1146 template <typename Print>
1147 class JsonWriter {
1148  public:
1149  explicit JsonWriter(Print &sink) : _sink(sink), _length(0) {}
1150  size_t bytesWritten() const {
1151  return _length;
1152  }
1153  void beginArray() {
1154  writeRaw('[');
1155  }
1156  void endArray() {
1157  writeRaw(']');
1158  }
1159  void beginObject() {
1160  writeRaw('{');
1161  }
1162  void endObject() {
1163  writeRaw('}');
1164  }
1165  void writeColon() {
1166  writeRaw(':');
1167  }
1168  void writeComma() {
1169  writeRaw(',');
1170  }
1171  void writeBoolean(bool value) {
1172  writeRaw(value ? "true" : "false");
1173  }
1174  void writeString(const char *value) {
1175  if (!value) {
1176  writeRaw("null");
1177  } else {
1178  writeRaw('\"');
1179  while (*value) writeChar(*value++);
1180  writeRaw('\"');
1181  }
1182  }
1183  void writeChar(char c) {
1184  char specialChar = Encoding::escapeChar(c);
1185  if (specialChar) {
1186  writeRaw('\\');
1187  writeRaw(specialChar);
1188  } else {
1189  writeRaw(c);
1190  }
1191  }
1192  template <typename TFloat>
1193  void writeFloat(TFloat value) {
1194  if (isNaN(value)) return writeRaw("NaN");
1195  if (value < 0.0) {
1196  writeRaw('-');
1197  value = -value;
1198  }
1199  if (isInfinity(value)) return writeRaw("Infinity");
1200  FloatParts<TFloat> parts(value);
1201  writeInteger(parts.integral);
1202  if (parts.decimalPlaces) writeDecimals(parts.decimal, parts.decimalPlaces);
1203  if (parts.exponent < 0) {
1204  writeRaw("e-");
1205  writeInteger(-parts.exponent);
1206  }
1207  if (parts.exponent > 0) {
1208  writeRaw('e');
1209  writeInteger(parts.exponent);
1210  }
1211  }
1212  template <typename UInt>
1213  void writeInteger(UInt value) {
1214  char buffer[22];
1215  char *end = buffer + sizeof(buffer) - 1;
1216  char *ptr = end;
1217  *ptr = 0;
1218  do {
1219  *--ptr = char(value % 10 + '0');
1220  value = UInt(value / 10);
1221  } while (value);
1222  writeRaw(ptr);
1223  }
1224  void writeDecimals(uint32_t value, int8_t width) {
1225  char buffer[16];
1226  char *ptr = buffer + sizeof(buffer) - 1;
1227  *ptr = 0;
1228  while (width--) {
1229  *--ptr = char(value % 10 + '0');
1230  value /= 10;
1231  }
1232  *--ptr = '.';
1233  writeRaw(ptr);
1234  }
1235  void writeRaw(const char *s) {
1236  _length += _sink.print(s);
1237  }
1238  void writeRaw(char c) {
1239  _length += _sink.print(c);
1240  }
1241  protected:
1242  Print &_sink;
1243  size_t _length;
1244  private:
1245  JsonWriter &operator=(const JsonWriter &); // cannot be assigned
1246 };
1247 }
1248 }
1249 namespace ArduinoJson {
1250 class JsonArray;
1251 class JsonObject;
1252 class JsonVariant;
1253 namespace Internals {
1254 class JsonArraySubscript;
1255 template <typename TKey>
1256 class JsonObjectSubscript;
1257 template <typename Writer>
1258 class JsonSerializer {
1259  public:
1260  static void serialize(const JsonArray &, Writer &);
1261  static void serialize(const JsonArraySubscript &, Writer &);
1262  static void serialize(const JsonObject &, Writer &);
1263  template <typename TKey>
1264  static void serialize(const JsonObjectSubscript<TKey> &, Writer &);
1265  static void serialize(const JsonVariant &, Writer &);
1266 };
1267 }
1268 }
1269 namespace ArduinoJson {
1270 namespace Internals {
1271 template <typename Print>
1272 class Prettyfier {
1273  public:
1274  explicit Prettyfier(IndentedPrint<Print>& p) : _sink(p) {
1275  _previousChar = 0;
1276  _inString = false;
1277  }
1278  size_t print(char c) {
1279  size_t n = _inString ? handleStringChar(c) : handleMarkupChar(c);
1280  _previousChar = c;
1281  return n;
1282  }
1283  size_t print(const char* s) {
1284  size_t n = 0;
1285  while (*s) n += print(*s++);
1286  return n;
1287  }
1288  private:
1289  Prettyfier& operator=(const Prettyfier&); // cannot be assigned
1290  bool inEmptyBlock() {
1291  return _previousChar == '{' || _previousChar == '[';
1292  }
1293  size_t handleStringChar(char c) {
1294  bool isQuote = c == '"' && _previousChar != '\\';
1295  if (isQuote) _inString = false;
1296  return _sink.print(c);
1297  }
1298  size_t handleMarkupChar(char c) {
1299  switch (c) {
1300  case '{':
1301  case '[':
1302  return writeBlockOpen(c);
1303  case '}':
1304  case ']':
1305  return writeBlockClose(c);
1306  case ':':
1307  return writeColon();
1308  case ',':
1309  return writeComma();
1310  case '"':
1311  return writeQuoteOpen();
1312  default:
1313  return writeNormalChar(c);
1314  }
1315  }
1316  size_t writeBlockClose(char c) {
1317  size_t n = 0;
1318  n += unindentIfNeeded();
1319  n += _sink.print(c);
1320  return n;
1321  }
1322  size_t writeBlockOpen(char c) {
1323  size_t n = 0;
1324  n += indentIfNeeded();
1325  n += _sink.print(c);
1326  return n;
1327  }
1328  size_t writeColon() {
1329  size_t n = 0;
1330  n += _sink.print(": ");
1331  return n;
1332  }
1333  size_t writeComma() {
1334  size_t n = 0;
1335  n += _sink.print(",\r\n");
1336  return n;
1337  }
1338  size_t writeQuoteOpen() {
1339  _inString = true;
1340  size_t n = 0;
1341  n += indentIfNeeded();
1342  n += _sink.print('"');
1343  return n;
1344  }
1345  size_t writeNormalChar(char c) {
1346  size_t n = 0;
1347  n += indentIfNeeded();
1348  n += _sink.print(c);
1349  return n;
1350  }
1351  size_t indentIfNeeded() {
1352  if (!inEmptyBlock()) return 0;
1353  _sink.indent();
1354  return _sink.print("\r\n");
1355  }
1356  size_t unindentIfNeeded() {
1357  if (inEmptyBlock()) return 0;
1358  _sink.unindent();
1359  return _sink.print("\r\n");
1360  }
1361  char _previousChar;
1362  IndentedPrint<Print>& _sink;
1363  bool _inString;
1364 };
1365 }
1366 }
1367 namespace ArduinoJson {
1368 namespace Internals {
1369 class StaticStringBuilder {
1370  public:
1371  StaticStringBuilder(char *buf, size_t size) : end(buf + size - 1), p(buf) {
1372  *p = '\0';
1373  }
1374  size_t print(char c) {
1375  if (p >= end) return 0;
1376  *p++ = c;
1377  *p = '\0';
1378  return 1;
1379  }
1380  size_t print(const char *s) {
1381  char *begin = p;
1382  while (p < end && *s) *p++ = *s++;
1383  *p = '\0';
1384  return size_t(p - begin);
1385  }
1386  private:
1387  char *end;
1388  char *p;
1389 };
1390 }
1391 }
1392 #if ARDUINOJSON_ENABLE_STD_STREAM
1393 #if ARDUINOJSON_ENABLE_STD_STREAM
1394 #include <ostream>
1395 namespace ArduinoJson {
1396 namespace Internals {
1397 class StreamPrintAdapter {
1398  public:
1399  explicit StreamPrintAdapter(std::ostream& os) : _os(os) {}
1400  size_t print(char c) {
1401  _os << c;
1402  return 1;
1403  }
1404  size_t print(const char* s) {
1405  _os << s;
1406  return strlen(s);
1407  }
1408  private:
1409  StreamPrintAdapter& operator=(const StreamPrintAdapter&);
1410  std::ostream& _os;
1411 };
1412 }
1413 }
1414 #endif // ARDUINOJSON_ENABLE_STD_STREAM
1415 #endif
1416 namespace ArduinoJson {
1417 namespace Internals {
1418 template <typename T>
1419 class JsonPrintable {
1420  public:
1421  template <typename Print>
1422  typename EnableIf<!StringTraits<Print>::has_append, size_t>::type printTo(
1423  Print &print) const {
1424  JsonWriter<Print> writer(print);
1425  JsonSerializer<JsonWriter<Print> >::serialize(downcast(), writer);
1426  return writer.bytesWritten();
1427  }
1428 #if ARDUINOJSON_ENABLE_STD_STREAM
1429  std::ostream &printTo(std::ostream &os) const {
1430  StreamPrintAdapter adapter(os);
1431  printTo(adapter);
1432  return os;
1433  }
1434 #endif
1435  size_t printTo(char *buffer, size_t bufferSize) const {
1436  StaticStringBuilder sb(buffer, bufferSize);
1437  return printTo(sb);
1438  }
1439  template <size_t N>
1440  size_t printTo(char (&buffer)[N]) const {
1441  return printTo(buffer, N);
1442  }
1443  template <typename TString>
1444  typename EnableIf<StringTraits<TString>::has_append, size_t>::type printTo(
1445  TString &str) const {
1446  DynamicStringBuilder<TString> sb(str);
1447  return printTo(sb);
1448  }
1449  template <typename Print>
1450  size_t prettyPrintTo(IndentedPrint<Print> &print) const {
1451  Prettyfier<Print> p(print);
1452  return printTo(p);
1453  }
1454  size_t prettyPrintTo(char *buffer, size_t bufferSize) const {
1455  StaticStringBuilder sb(buffer, bufferSize);
1456  return prettyPrintTo(sb);
1457  }
1458  template <size_t N>
1459  size_t prettyPrintTo(char (&buffer)[N]) const {
1460  return prettyPrintTo(buffer, N);
1461  }
1462  template <typename Print>
1463  typename EnableIf<!StringTraits<Print>::has_append, size_t>::type
1464  prettyPrintTo(Print &print) const {
1465  IndentedPrint<Print> indentedPrint(print);
1466  return prettyPrintTo(indentedPrint);
1467  }
1468  template <typename TString>
1469  typename EnableIf<StringTraits<TString>::has_append, size_t>::type
1470  prettyPrintTo(TString &str) const {
1471  DynamicStringBuilder<TString> sb(str);
1472  return prettyPrintTo(sb);
1473  }
1474  size_t measureLength() const {
1475  DummyPrint dp;
1476  return printTo(dp);
1477  }
1478  size_t measurePrettyLength() const {
1479  DummyPrint dp;
1480  return prettyPrintTo(dp);
1481  }
1482  private:
1483  const T &downcast() const {
1484  return *static_cast<const T *>(this);
1485  }
1486 };
1487 #if ARDUINOJSON_ENABLE_STD_STREAM
1488 template <typename T>
1489 inline std::ostream &operator<<(std::ostream &os, const JsonPrintable<T> &v) {
1490  return v.printTo(os);
1491 }
1492 #endif
1493 }
1494 }
1495 namespace ArduinoJson {
1496 namespace Internals {
1497 template <typename TImpl>
1498 class JsonVariantBase : public JsonPrintable<TImpl>,
1499  public JsonVariantCasts<TImpl>,
1500  public JsonVariantComparisons<TImpl>,
1501  public JsonVariantOr<TImpl>,
1502  public JsonVariantSubscripts<TImpl>,
1503  public JsonVariantTag {};
1504 }
1505 }
1506 namespace ArduinoJson {
1507 namespace Internals {
1508 template <typename T>
1509 class RawJsonString {
1510  public:
1511  explicit RawJsonString(T str) : _str(str) {}
1512  operator T() const {
1513  return _str;
1514  }
1515  private:
1516  T _str;
1517 };
1518 template <typename String>
1519 struct StringTraits<RawJsonString<String>, void> {
1520  static bool is_null(RawJsonString<String> source) {
1521  return StringTraits<String>::is_null(static_cast<String>(source));
1522  }
1523  typedef RawJsonString<const char*> duplicate_t;
1524  template <typename Buffer>
1525  static duplicate_t duplicate(RawJsonString<String> source, Buffer* buffer) {
1526  return duplicate_t(StringTraits<String>::duplicate(source, buffer));
1527  }
1528  static const bool has_append = false;
1529  static const bool has_equals = false;
1530  static const bool should_duplicate = StringTraits<String>::should_duplicate;
1531 };
1532 }
1533 template <typename T>
1534 inline Internals::RawJsonString<T> RawJson(T str) {
1535  return Internals::RawJsonString<T>(str);
1536 }
1537 }
1538 namespace ArduinoJson {
1539 namespace Internals {
1540 template <typename T>
1541 struct IsFloatingPoint {
1542  static const bool value = IsSame<T, float>::value || IsSame<T, double>::value;
1543 };
1544 }
1545 }
1546 namespace ArduinoJson {
1547 namespace Internals {
1548 template <typename T>
1549 struct RemoveConst {
1550  typedef T type;
1551 };
1552 template <typename T>
1553 struct RemoveConst<const T> {
1554  typedef T type;
1555 };
1556 }
1557 }
1558 namespace ArduinoJson {
1559 class JsonArray;
1560 class JsonObject;
1561 class JsonVariant : public Internals::JsonVariantBase<JsonVariant> {
1562  template <typename Print>
1563  friend class Internals::JsonSerializer;
1564  public:
1565  JsonVariant() : _type(Internals::JSON_UNDEFINED) {}
1566  JsonVariant(bool value) {
1567  using namespace Internals;
1568  _type = JSON_BOOLEAN;
1569  _content.asInteger = static_cast<JsonUInt>(value);
1570  }
1571  template <typename T>
1572  JsonVariant(T value, typename Internals::EnableIf<
1573  Internals::IsFloatingPoint<T>::value>::type * = 0) {
1574  using namespace Internals;
1575  _type = JSON_FLOAT;
1576  _content.asFloat = static_cast<JsonFloat>(value);
1577  }
1578  template <typename T>
1579  DEPRECATED("Second argument is not supported anymore")
1580  JsonVariant(T value, uint8_t,
1581  typename Internals::EnableIf<
1582  Internals::IsFloatingPoint<T>::value>::type * = 0) {
1583  using namespace Internals;
1584  _type = JSON_FLOAT;
1585  _content.asFloat = static_cast<JsonFloat>(value);
1586  }
1587  template <typename T>
1588  JsonVariant(
1589  T value,
1590  typename Internals::EnableIf<Internals::IsSignedIntegral<T>::value ||
1591  Internals::IsSame<T, char>::value>::type * =
1592  0) {
1593  using namespace Internals;
1594  if (value >= 0) {
1595  _type = JSON_POSITIVE_INTEGER;
1596  _content.asInteger = static_cast<JsonUInt>(value);
1597  } else {
1598  _type = JSON_NEGATIVE_INTEGER;
1599  _content.asInteger = static_cast<JsonUInt>(-value);
1600  }
1601  }
1602  template <typename T>
1603  JsonVariant(T value,
1604  typename Internals::EnableIf<
1605  Internals::IsUnsignedIntegral<T>::value>::type * = 0) {
1606  using namespace Internals;
1607  _type = JSON_POSITIVE_INTEGER;
1608  _content.asInteger = static_cast<JsonUInt>(value);
1609  }
1610  template <typename TChar>
1611  JsonVariant(
1612  const TChar *value,
1613  typename Internals::EnableIf<Internals::IsChar<TChar>::value>::type * =
1614  0) {
1615  _type = Internals::JSON_STRING;
1616  _content.asString = reinterpret_cast<const char *>(value);
1617  }
1618  JsonVariant(Internals::RawJsonString<const char *> value) {
1619  _type = Internals::JSON_UNPARSED;
1620  _content.asString = value;
1621  }
1622  JsonVariant(const JsonArray &array);
1623  JsonVariant(const JsonObject &object);
1624  template <typename T>
1625  const typename Internals::EnableIf<Internals::IsIntegral<T>::value, T>::type
1626  as() const {
1627  return variantAsInteger<T>();
1628  }
1629  template <typename T>
1630  const typename Internals::EnableIf<Internals::IsSame<T, bool>::value, T>::type
1631  as() const {
1632  return variantAsInteger<int>() != 0;
1633  }
1634  template <typename T>
1635  const typename Internals::EnableIf<Internals::IsFloatingPoint<T>::value,
1636  T>::type
1637  as() const {
1638  return variantAsFloat<T>();
1639  }
1640  template <typename T>
1641  typename Internals::EnableIf<Internals::IsSame<T, const char *>::value ||
1642  Internals::IsSame<T, char *>::value,
1643  const char *>::type
1644  as() const {
1645  return variantAsString();
1646  }
1647  template <typename T>
1648  typename Internals::EnableIf<Internals::StringTraits<T>::has_append, T>::type
1649  as() const {
1650  const char *cstr = variantAsString();
1651  if (cstr) return T(cstr);
1652  T s;
1653  printTo(s);
1654  return s;
1655  }
1656  template <typename T>
1657  typename Internals::EnableIf<
1658  Internals::IsSame<typename Internals::RemoveReference<T>::type,
1659  JsonArray>::value,
1660  JsonArray &>::type
1661  as() const {
1662  return variantAsArray();
1663  }
1664  template <typename T>
1665  typename Internals::EnableIf<
1666  Internals::IsSame<typename Internals::RemoveReference<T>::type,
1667  const JsonArray>::value,
1668  const JsonArray &>::type
1669  as() const {
1670  return variantAsArray();
1671  }
1672  template <typename T>
1673  typename Internals::EnableIf<
1674  Internals::IsSame<typename Internals::RemoveReference<T>::type,
1675  JsonObject>::value,
1676  JsonObject &>::type
1677  as() const {
1678  return variantAsObject();
1679  }
1680  template <typename T>
1681  typename Internals::EnableIf<
1682  Internals::IsSame<typename Internals::RemoveReference<T>::type,
1683  const JsonObject>::value,
1684  const JsonObject &>::type
1685  as() const {
1686  return variantAsObject();
1687  }
1688  template <typename T>
1689  typename Internals::EnableIf<Internals::IsSame<T, JsonVariant>::value,
1690  T>::type
1691  as() const {
1692  return *this;
1693  }
1694  template <typename T>
1695  typename Internals::EnableIf<Internals::IsIntegral<T>::value, bool>::type is()
1696  const {
1697  return variantIsInteger();
1698  }
1699  template <typename T>
1700  typename Internals::EnableIf<Internals::IsFloatingPoint<T>::value, bool>::type
1701  is() const {
1702  return variantIsFloat();
1703  }
1704  template <typename T>
1705  typename Internals::EnableIf<Internals::IsSame<T, bool>::value, bool>::type
1706  is() const {
1707  return variantIsBoolean();
1708  }
1709  template <typename T>
1710  typename Internals::EnableIf<Internals::IsSame<T, const char *>::value ||
1711  Internals::IsSame<T, char *>::value ||
1712  Internals::StringTraits<T>::has_append,
1713  bool>::type
1714  is() const {
1715  return variantIsString();
1716  }
1717  template <typename T>
1718  typename Internals::EnableIf<
1719  Internals::IsSame<typename Internals::RemoveConst<
1720  typename Internals::RemoveReference<T>::type>::type,
1721  JsonArray>::value,
1722  bool>::type
1723  is() const {
1724  return variantIsArray();
1725  }
1726  template <typename T>
1727  typename Internals::EnableIf<
1728  Internals::IsSame<typename Internals::RemoveConst<
1729  typename Internals::RemoveReference<T>::type>::type,
1730  JsonObject>::value,
1731  bool>::type
1732  is() const {
1733  return variantIsObject();
1734  }
1735  bool success() const {
1736  return _type != Internals::JSON_UNDEFINED;
1737  }
1738  private:
1739  JsonArray &variantAsArray() const;
1740  JsonObject &variantAsObject() const;
1741  const char *variantAsString() const;
1742  template <typename T>
1743  T variantAsFloat() const;
1744  template <typename T>
1745  T variantAsInteger() const;
1746  bool variantIsBoolean() const;
1747  bool variantIsFloat() const;
1748  bool variantIsInteger() const;
1749  bool variantIsArray() const {
1750  return _type == Internals::JSON_ARRAY;
1751  }
1752  bool variantIsObject() const {
1753  return _type == Internals::JSON_OBJECT;
1754  }
1755  bool variantIsString() const {
1756  return _type == Internals::JSON_STRING ||
1757  (_type == Internals::JSON_UNPARSED && _content.asString &&
1758  !strcmp("null", _content.asString));
1759  }
1760  Internals::JsonVariantType _type;
1761  Internals::JsonVariantContent _content;
1762 };
1763 DEPRECATED("Decimal places are ignored, use the float value instead")
1764 inline JsonVariant float_with_n_digits(float value, uint8_t) {
1765  return JsonVariant(value);
1766 }
1767 DEPRECATED("Decimal places are ignored, use the double value instead")
1768 inline JsonVariant double_with_n_digits(double value, uint8_t) {
1769  return JsonVariant(value);
1770 }
1771 } // namespace ArduinoJson
1772 namespace ArduinoJson {
1773 namespace Internals {
1774 template <typename T>
1775 struct IsArray {
1776  static const bool value = false;
1777 };
1778 template <typename T>
1779 struct IsArray<T[]> {
1780  static const bool value = true;
1781 };
1782 template <typename T, size_t N>
1783 struct IsArray<T[N]> {
1784  static const bool value = true;
1785 };
1786 }
1787 }
1788 namespace ArduinoJson {
1789 class JsonArray;
1790 class JsonObject;
1791 class JsonBuffer : Internals::NonCopyable {
1792  public:
1793  JsonArray &createArray();
1794  JsonObject &createObject();
1795  template <typename TString>
1796  DEPRECATED("char* are duplicated, you don't need strdup() anymore")
1797  typename Internals::EnableIf<!Internals::IsArray<TString>::value,
1798  const char *>::type strdup(const TString &src) {
1799  return Internals::StringTraits<TString>::duplicate(src, this);
1800  }
1801  template <typename TString>
1802  DEPRECATED("char* are duplicated, you don't need strdup() anymore")
1803  const char *strdup(TString *src) {
1804  return Internals::StringTraits<TString *>::duplicate(src, this);
1805  }
1806  virtual void *alloc(size_t size) = 0;
1807  protected:
1808  ~JsonBuffer() {}
1809  static FORCE_INLINE size_t round_size_up(size_t bytes) {
1810 #if ARDUINOJSON_ENABLE_ALIGNMENT
1811  const size_t x = sizeof(void *) - 1;
1812  return (bytes + x) & ~x;
1813 #else
1814  return bytes;
1815 #endif
1816  }
1817 };
1818 }
1819 namespace ArduinoJson {
1820 namespace Internals {
1821 template <typename TChar>
1822 class StringWriter {
1823  public:
1824  class String {
1825  public:
1826  String(TChar** ptr) : _writePtr(ptr), _startPtr(*ptr) {}
1827  void append(char c) {
1828  *(*_writePtr)++ = TChar(c);
1829  }
1830  const char* c_str() const {
1831  *(*_writePtr)++ = 0;
1832  return reinterpret_cast<const char*>(_startPtr);
1833  }
1834  private:
1835  TChar** _writePtr;
1836  TChar* _startPtr;
1837  };
1838  StringWriter(TChar* buffer) : _ptr(buffer) {}
1839  String startString() {
1840  return String(&_ptr);
1841  }
1842  private:
1843  TChar* _ptr;
1844 };
1845 }
1846 }
1847 namespace ArduinoJson {
1848 namespace Internals {
1849 template <typename TReader, typename TWriter>
1850 class JsonParser {
1851  public:
1852  JsonParser(JsonBuffer *buffer, TReader reader, TWriter writer,
1853  uint8_t nestingLimit)
1854  : _buffer(buffer),
1855  _reader(reader),
1856  _writer(writer),
1857  _nestingLimit(nestingLimit) {}
1858  JsonArray &parseArray();
1859  JsonObject &parseObject();
1860  JsonVariant parseVariant() {
1861  JsonVariant result;
1862  parseAnythingTo(&result);
1863  return result;
1864  }
1865  private:
1866  JsonParser &operator=(const JsonParser &); // non-copiable
1867  static bool eat(TReader &, char charToSkip);
1868  FORCE_INLINE bool eat(char charToSkip) {
1869  return eat(_reader, charToSkip);
1870  }
1871  const char *parseString();
1872  bool parseAnythingTo(JsonVariant *destination);
1873  inline bool parseArrayTo(JsonVariant *destination);
1874  inline bool parseObjectTo(JsonVariant *destination);
1875  inline bool parseStringTo(JsonVariant *destination);
1876  static inline bool isBetween(char c, char min, char max) {
1877  return min <= c && c <= max;
1878  }
1879  static inline bool canBeInNonQuotedString(char c) {
1880  return isBetween(c, '0', '9') || isBetween(c, '_', 'z') ||
1881  isBetween(c, 'A', 'Z') || c == '+' || c == '-' || c == '.';
1882  }
1883  static inline bool isQuote(char c) {
1884  return c == '\'' || c == '\"';
1885  }
1886  JsonBuffer *_buffer;
1887  TReader _reader;
1888  TWriter _writer;
1889  uint8_t _nestingLimit;
1890 };
1891 template <typename TJsonBuffer, typename TString, typename Enable = void>
1892 struct JsonParserBuilder {
1893  typedef typename StringTraits<TString>::Reader InputReader;
1894  typedef JsonParser<InputReader, TJsonBuffer &> TParser;
1895  static TParser makeParser(TJsonBuffer *buffer, TString &json,
1896  uint8_t nestingLimit) {
1897  return TParser(buffer, InputReader(json), *buffer, nestingLimit);
1898  }
1899 };
1900 template <typename TJsonBuffer, typename TChar>
1901 struct JsonParserBuilder<TJsonBuffer, TChar *,
1902  typename EnableIf<!IsConst<TChar>::value>::type> {
1903  typedef typename StringTraits<TChar *>::Reader TReader;
1904  typedef StringWriter<TChar> TWriter;
1905  typedef JsonParser<TReader, TWriter> TParser;
1906  static TParser makeParser(TJsonBuffer *buffer, TChar *json,
1907  uint8_t nestingLimit) {
1908  return TParser(buffer, TReader(json), TWriter(json), nestingLimit);
1909  }
1910 };
1911 template <typename TJsonBuffer, typename TString>
1912 inline typename JsonParserBuilder<TJsonBuffer, TString>::TParser makeParser(
1913  TJsonBuffer *buffer, TString &json, uint8_t nestingLimit) {
1914  return JsonParserBuilder<TJsonBuffer, TString>::makeParser(buffer, json,
1915  nestingLimit);
1916 }
1917 } // namespace Internals
1918 } // namespace ArduinoJson
1919 namespace ArduinoJson {
1920 namespace Internals {
1921 template <typename TDerived>
1922 class JsonBufferBase : public JsonBuffer {
1923  public:
1924  template <typename TString>
1925  typename Internals::EnableIf<!Internals::IsArray<TString>::value,
1926  JsonArray &>::type
1927  parseArray(const TString &json,
1928  uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1929  return Internals::makeParser(that(), json, nestingLimit).parseArray();
1930  }
1931  template <typename TString>
1932  JsonArray &parseArray(
1933  TString *json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1934  return Internals::makeParser(that(), json, nestingLimit).parseArray();
1935  }
1936  template <typename TString>
1937  JsonArray &parseArray(
1938  TString &json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1939  return Internals::makeParser(that(), json, nestingLimit).parseArray();
1940  }
1941  template <typename TString>
1942  typename Internals::EnableIf<!Internals::IsArray<TString>::value,
1943  JsonObject &>::type
1944  parseObject(const TString &json,
1945  uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1946  return Internals::makeParser(that(), json, nestingLimit).parseObject();
1947  }
1948  template <typename TString>
1949  JsonObject &parseObject(
1950  TString *json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1951  return Internals::makeParser(that(), json, nestingLimit).parseObject();
1952  }
1953  template <typename TString>
1954  JsonObject &parseObject(
1955  TString &json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1956  return Internals::makeParser(that(), json, nestingLimit).parseObject();
1957  }
1958  template <typename TString>
1959  typename Internals::EnableIf<!Internals::IsArray<TString>::value,
1960  JsonVariant>::type
1961  parse(const TString &json,
1962  uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1963  return Internals::makeParser(that(), json, nestingLimit).parseVariant();
1964  }
1965  template <typename TString>
1966  JsonVariant parse(TString *json,
1967  uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1968  return Internals::makeParser(that(), json, nestingLimit).parseVariant();
1969  }
1970  template <typename TString>
1971  JsonVariant parse(TString &json,
1972  uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
1973  return Internals::makeParser(that(), json, nestingLimit).parseVariant();
1974  }
1975  protected:
1976  ~JsonBufferBase() {}
1977  private:
1978  TDerived *that() {
1979  return static_cast<TDerived *>(this);
1980  }
1981 };
1982 }
1983 }
1984 #if defined(__clang__)
1985 #pragma clang diagnostic push
1986 #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
1987 #elif defined(__GNUC__)
1988 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
1989 #pragma GCC diagnostic push
1990 #endif
1991 #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
1992 #endif
1993 namespace ArduinoJson {
1994 namespace Internals {
1995 class DefaultAllocator {
1996  public:
1997  void* allocate(size_t size) {
1998  return malloc(size);
1999  }
2000  void deallocate(void* pointer) {
2001  free(pointer);
2002  }
2003 };
2004 template <typename TAllocator>
2005 class DynamicJsonBufferBase
2006  : public JsonBufferBase<DynamicJsonBufferBase<TAllocator> > {
2007  struct Block;
2008  struct EmptyBlock {
2009  Block* next;
2010  size_t capacity;
2011  size_t size;
2012  };
2013  struct Block : EmptyBlock {
2014  uint8_t data[1];
2015  };
2016  public:
2017  enum { EmptyBlockSize = sizeof(EmptyBlock) };
2018  DynamicJsonBufferBase(size_t initialSize = 256)
2019  : _head(NULL), _nextBlockCapacity(initialSize) {}
2020  ~DynamicJsonBufferBase() {
2021  clear();
2022  }
2023  size_t size() const {
2024  size_t total = 0;
2025  for (const Block* b = _head; b; b = b->next) total += b->size;
2026  return total;
2027  }
2028  virtual void* alloc(size_t bytes) {
2029  alignNextAlloc();
2030  return canAllocInHead(bytes) ? allocInHead(bytes) : allocInNewBlock(bytes);
2031  }
2032  void clear() {
2033  Block* currentBlock = _head;
2034  while (currentBlock != NULL) {
2035  _nextBlockCapacity = currentBlock->capacity;
2036  Block* nextBlock = currentBlock->next;
2037  _allocator.deallocate(currentBlock);
2038  currentBlock = nextBlock;
2039  }
2040  _head = 0;
2041  }
2042  class String {
2043  public:
2044  String(DynamicJsonBufferBase* parent)
2045  : _parent(parent), _start(NULL), _length(0) {}
2046  void append(char c) {
2047  if (_parent->canAllocInHead(1)) {
2048  char* end = static_cast<char*>(_parent->allocInHead(1));
2049  *end = c;
2050  if (_length == 0) _start = end;
2051  } else {
2052  char* newStart =
2053  static_cast<char*>(_parent->allocInNewBlock(_length + 1));
2054  if (_start && newStart) memcpy(newStart, _start, _length);
2055  if (newStart) newStart[_length] = c;
2056  _start = newStart;
2057  }
2058  _length++;
2059  }
2060  const char* c_str() {
2061  append(0);
2062  return _start;
2063  }
2064  private:
2065  DynamicJsonBufferBase* _parent;
2066  char* _start;
2067  size_t _length;
2068  };
2069  String startString() {
2070  return String(this);
2071  }
2072  private:
2073  void alignNextAlloc() {
2074  if (_head) _head->size = this->round_size_up(_head->size);
2075  }
2076  bool canAllocInHead(size_t bytes) const {
2077  return _head != NULL && _head->size + bytes <= _head->capacity;
2078  }
2079  void* allocInHead(size_t bytes) {
2080  void* p = _head->data + _head->size;
2081  _head->size += bytes;
2082  return p;
2083  }
2084  void* allocInNewBlock(size_t bytes) {
2085  size_t capacity = _nextBlockCapacity;
2086  if (bytes > capacity) capacity = bytes;
2087  if (!addNewBlock(capacity)) return NULL;
2088  _nextBlockCapacity *= 2;
2089  return allocInHead(bytes);
2090  }
2091  bool addNewBlock(size_t capacity) {
2092  size_t bytes = EmptyBlockSize + capacity;
2093  Block* block = static_cast<Block*>(_allocator.allocate(bytes));
2094  if (block == NULL) return false;
2095  block->capacity = capacity;
2096  block->size = 0;
2097  block->next = _head;
2098  _head = block;
2099  return true;
2100  }
2101  TAllocator _allocator;
2102  Block* _head;
2103  size_t _nextBlockCapacity;
2104 };
2105 }
2106 #if defined(__clang__)
2107 #pragma clang diagnostic pop
2108 #elif defined(__GNUC__)
2109 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
2110 #pragma GCC diagnostic pop
2111 #endif
2112 #endif
2113 typedef Internals::DynamicJsonBufferBase<Internals::DefaultAllocator>
2114  DynamicJsonBuffer;
2115 }
2116 namespace ArduinoJson {
2117 namespace Internals {
2118 class JsonBufferAllocated {
2119  public:
2120  void *operator new(size_t n, JsonBuffer *jsonBuffer) throw() {
2121  if (!jsonBuffer) return NULL;
2122  return jsonBuffer->alloc(n);
2123  }
2124  void operator delete(void *, JsonBuffer *)throw();
2125 };
2126 }
2127 }
2128 namespace ArduinoJson {
2129 namespace Internals {
2130 template <typename T>
2131 struct ListNode : public Internals::JsonBufferAllocated {
2132  ListNode() throw() : next(NULL) {}
2133  ListNode<T> *next;
2134  T content;
2135 };
2136 }
2137 }
2138 namespace ArduinoJson {
2139 namespace Internals {
2140 template <typename T>
2141 class ListConstIterator {
2142  public:
2143  explicit ListConstIterator(const ListNode<T> *node = NULL) : _node(node) {}
2144  const T &operator*() const {
2145  return _node->content;
2146  }
2147  const T *operator->() {
2148  return &_node->content;
2149  }
2150  bool operator==(const ListConstIterator<T> &other) const {
2151  return _node == other._node;
2152  }
2153  bool operator!=(const ListConstIterator<T> &other) const {
2154  return _node != other._node;
2155  }
2156  ListConstIterator<T> &operator++() {
2157  if (_node) _node = _node->next;
2158  return *this;
2159  }
2160  ListConstIterator<T> &operator+=(size_t distance) {
2161  while (_node && distance) {
2162  _node = _node->next;
2163  --distance;
2164  }
2165  return *this;
2166  }
2167  private:
2168  const ListNode<T> *_node;
2169 };
2170 }
2171 }
2172 namespace ArduinoJson {
2173 namespace Internals {
2174 template <typename T>
2175 class List;
2176 template <typename T>
2177 class ListIterator {
2178  friend class List<T>;
2179  public:
2180  explicit ListIterator(ListNode<T> *node = NULL) : _node(node) {}
2181  T &operator*() const {
2182  return _node->content;
2183  }
2184  T *operator->() {
2185  return &_node->content;
2186  }
2187  bool operator==(const ListIterator<T> &other) const {
2188  return _node == other._node;
2189  }
2190  bool operator!=(const ListIterator<T> &other) const {
2191  return _node != other._node;
2192  }
2193  ListIterator<T> &operator++() {
2194  if (_node) _node = _node->next;
2195  return *this;
2196  }
2197  ListIterator<T> &operator+=(size_t distance) {
2198  while (_node && distance) {
2199  _node = _node->next;
2200  --distance;
2201  }
2202  return *this;
2203  }
2204  operator ListConstIterator<T>() const {
2205  return ListConstIterator<T>(_node);
2206  }
2207  private:
2208  ListNode<T> *_node;
2209 };
2210 }
2211 }
2212 namespace ArduinoJson {
2213 namespace Internals {
2214 template <typename T>
2215 class List {
2216  public:
2217  typedef T value_type;
2218  typedef ListNode<T> node_type;
2219  typedef ListIterator<T> iterator;
2220  typedef ListConstIterator<T> const_iterator;
2221  explicit List(JsonBuffer *buffer) : _buffer(buffer), _firstNode(NULL) {}
2222  bool success() const {
2223  return _buffer != NULL;
2224  }
2225  size_t size() const {
2226  size_t nodeCount = 0;
2227  for (node_type *node = _firstNode; node; node = node->next) nodeCount++;
2228  return nodeCount;
2229  }
2230  iterator add() {
2231  node_type *newNode = new (_buffer) node_type();
2232  if (_firstNode) {
2233  node_type *lastNode = _firstNode;
2234  while (lastNode->next) lastNode = lastNode->next;
2235  lastNode->next = newNode;
2236  } else {
2237  _firstNode = newNode;
2238  }
2239  return iterator(newNode);
2240  }
2241  iterator begin() {
2242  return iterator(_firstNode);
2243  }
2244  iterator end() {
2245  return iterator(NULL);
2246  }
2247  const_iterator begin() const {
2248  return const_iterator(_firstNode);
2249  }
2250  const_iterator end() const {
2251  return const_iterator(NULL);
2252  }
2253  void remove(iterator it) {
2254  node_type *nodeToRemove = it._node;
2255  if (!nodeToRemove) return;
2256  if (nodeToRemove == _firstNode) {
2257  _firstNode = nodeToRemove->next;
2258  } else {
2259  for (node_type *node = _firstNode; node; node = node->next)
2260  if (node->next == nodeToRemove) node->next = nodeToRemove->next;
2261  }
2262  }
2263  protected:
2264  JsonBuffer *_buffer;
2265  private:
2266  node_type *_firstNode;
2267 };
2268 }
2269 }
2270 namespace ArduinoJson {
2271 namespace Internals {
2272 class ReferenceType {
2273  public:
2274  bool operator==(const ReferenceType& other) const {
2275  return this == &other;
2276  }
2277  bool operator!=(const ReferenceType& other) const {
2278  return this != &other;
2279  }
2280 };
2281 }
2282 }
2283 namespace ArduinoJson {
2284 namespace Internals {
2285 template <typename Source, typename Enable = void>
2286 struct ValueSaver {
2287  template <typename Destination>
2288  static bool save(JsonBuffer*, Destination& destination, Source source) {
2289  destination = source;
2290  return true;
2291  }
2292 };
2293 template <typename Source>
2294 struct ValueSaver<
2295  Source, typename EnableIf<StringTraits<Source>::should_duplicate>::type> {
2296  template <typename Destination>
2297  static bool save(JsonBuffer* buffer, Destination& dest, Source source) {
2298  if (!StringTraits<Source>::is_null(source)) {
2299  typename StringTraits<Source>::duplicate_t dup =
2300  StringTraits<Source>::duplicate(source, buffer);
2301  if (!dup) return false;
2302  dest = dup;
2303  } else {
2304  dest = reinterpret_cast<const char*>(0);
2305  }
2306  return true;
2307  }
2308 };
2309 template <typename Char>
2310 struct ValueSaver<
2311  Char*, typename EnableIf<!StringTraits<Char*>::should_duplicate>::type> {
2312  template <typename Destination>
2313  static bool save(JsonBuffer*, Destination& dest, Char* source) {
2314  dest = reinterpret_cast<const char*>(source);
2315  return true;
2316  }
2317 };
2318 }
2319 }
2320 #define JSON_ARRAY_SIZE(NUMBER_OF_ELEMENTS) \
2321  (sizeof(JsonArray) + (NUMBER_OF_ELEMENTS) * sizeof(JsonArray::node_type))
2322 namespace ArduinoJson {
2323 class JsonObject;
2324 class JsonBuffer;
2325 namespace Internals {
2326 class JsonArraySubscript;
2327 }
2328 class JsonArray : public Internals::JsonPrintable<JsonArray>,
2329  public Internals::ReferenceType,
2330  public Internals::NonCopyable,
2331  public Internals::List<JsonVariant>,
2332  public Internals::JsonBufferAllocated {
2333  public:
2334  explicit JsonArray(JsonBuffer *buffer) throw()
2335  : Internals::List<JsonVariant>(buffer) {}
2336  const Internals::JsonArraySubscript operator[](size_t index) const;
2337  Internals::JsonArraySubscript operator[](size_t index);
2338  template <typename T>
2339  bool add(const T &value) {
2340  return add_impl<const T &>(value);
2341  }
2342  template <typename T>
2343  bool add(T *value) {
2344  return add_impl<T *>(value);
2345  }
2346  template <typename T>
2347  DEPRECATED("Second argument is not supported anymore")
2348  bool add(T value, uint8_t) {
2349  return add_impl<const JsonVariant &>(JsonVariant(value));
2350  }
2351  template <typename T>
2352  bool set(size_t index, const T &value) {
2353  return set_impl<const T &>(index, value);
2354  }
2355  template <typename T>
2356  bool set(size_t index, T *value) {
2357  return set_impl<T *>(index, value);
2358  }
2359  template <typename T>
2360  typename Internals::EnableIf<Internals::IsFloatingPoint<T>::value, bool>::type
2361  set(size_t index, T value, uint8_t decimals) {
2362  return set_impl<const JsonVariant &>(index, JsonVariant(value, decimals));
2363  }
2364  template <typename T>
2365  typename Internals::JsonVariantAs<T>::type get(size_t index) const {
2366  const_iterator it = begin() += index;
2367  return it != end() ? it->as<T>() : Internals::JsonVariantDefault<T>::get();
2368  }
2369  template <typename T>
2370  bool is(size_t index) const {
2371  const_iterator it = begin() += index;
2372  return it != end() ? it->is<T>() : false;
2373  }
2374  JsonArray &createNestedArray();
2375  JsonObject &createNestedObject();
2376  void remove(size_t index) {
2377  remove(begin() += index);
2378  }
2379  using Internals::List<JsonVariant>::remove;
2380  static JsonArray &invalid() {
2381  static JsonArray instance(NULL);
2382  return instance;
2383  }
2384  template <typename T, size_t N>
2385  bool copyFrom(T (&array)[N]) {
2386  return copyFrom(array, N);
2387  }
2388  template <typename T>
2389  bool copyFrom(T *array, size_t len) {
2390  bool ok = true;
2391  for (size_t i = 0; i < len; i++) {
2392  ok &= add(array[i]);
2393  }
2394  return ok;
2395  }
2396  template <typename T, size_t N1, size_t N2>
2397  bool copyFrom(T (&array)[N1][N2]) {
2398  bool ok = true;
2399  for (size_t i = 0; i < N1; i++) {
2400  JsonArray &nestedArray = createNestedArray();
2401  for (size_t j = 0; j < N2; j++) {
2402  ok &= nestedArray.add(array[i][j]);
2403  }
2404  }
2405  return ok;
2406  }
2407  template <typename T, size_t N>
2408  size_t copyTo(T (&array)[N]) const {
2409  return copyTo(array, N);
2410  }
2411  template <typename T>
2412  size_t copyTo(T *array, size_t len) const {
2413  size_t i = 0;
2414  for (const_iterator it = begin(); it != end() && i < len; ++it)
2415  array[i++] = *it;
2416  return i;
2417  }
2418  template <typename T, size_t N1, size_t N2>
2419  void copyTo(T (&array)[N1][N2]) const {
2420  size_t i = 0;
2421  for (const_iterator it = begin(); it != end() && i < N1; ++it) {
2422  it->as<JsonArray>().copyTo(array[i++]);
2423  }
2424  }
2425 #if ARDUINOJSON_ENABLE_DEPRECATED
2426  DEPRECATED("use remove() instead")
2427  FORCE_INLINE void removeAt(size_t index) {
2428  return remove(index);
2429  }
2430 #endif
2431  private:
2432  template <typename TValueRef>
2433  bool set_impl(size_t index, TValueRef value) {
2434  iterator it = begin() += index;
2435  if (it == end()) return false;
2436  return Internals::ValueSaver<TValueRef>::save(_buffer, *it, value);
2437  }
2438  template <typename TValueRef>
2439  bool add_impl(TValueRef value) {
2440  iterator it = Internals::List<JsonVariant>::add();
2441  if (it == end()) return false;
2442  return Internals::ValueSaver<TValueRef>::save(_buffer, *it, value);
2443  }
2444 };
2445 namespace Internals {
2446 template <>
2447 struct JsonVariantDefault<JsonArray> {
2448  static JsonArray &get() {
2449  return JsonArray::invalid();
2450  }
2451 };
2452 }
2453 }
2454 namespace ArduinoJson {
2455 struct JsonPair {
2456  const char* key;
2457  JsonVariant value;
2458 };
2459 }
2460 #define JSON_OBJECT_SIZE(NUMBER_OF_ELEMENTS) \
2461  (sizeof(JsonObject) + (NUMBER_OF_ELEMENTS) * sizeof(JsonObject::node_type))
2462 namespace ArduinoJson {
2463 class JsonArray;
2464 class JsonBuffer;
2465 namespace Internals {
2466 template <typename>
2467 class JsonObjectSubscript;
2468 }
2469 class JsonObject : public Internals::JsonPrintable<JsonObject>,
2470  public Internals::ReferenceType,
2471  public Internals::NonCopyable,
2472  public Internals::List<JsonPair>,
2473  public Internals::JsonBufferAllocated {
2474  public:
2475  explicit JsonObject(JsonBuffer* buffer) throw()
2476  : Internals::List<JsonPair>(buffer) {}
2477  template <typename TString>
2478  Internals::JsonObjectSubscript<const TString&> operator[](
2479  const TString& key) {
2480  return Internals::JsonObjectSubscript<const TString&>(*this, key);
2481  }
2482  template <typename TString>
2483  Internals::JsonObjectSubscript<TString*> operator[](TString* key) {
2484  return Internals::JsonObjectSubscript<TString*>(*this, key);
2485  }
2486  template <typename TString>
2487  const Internals::JsonObjectSubscript<const TString&> operator[](
2488  const TString& key) const {
2489  return Internals::JsonObjectSubscript<const TString&>(
2490  *const_cast<JsonObject*>(this), key);
2491  }
2492  template <typename TString>
2493  const Internals::JsonObjectSubscript<TString*> operator[](
2494  TString* key) const {
2495  return Internals::JsonObjectSubscript<TString*>(
2496  *const_cast<JsonObject*>(this), key);
2497  }
2498  template <typename TValue, typename TString>
2499  bool set(const TString& key, const TValue& value) {
2500  return set_impl<const TString&, const TValue&>(key, value);
2501  }
2502  template <typename TValue, typename TString>
2503  bool set(const TString& key, TValue* value) {
2504  return set_impl<const TString&, TValue*>(key, value);
2505  }
2506  template <typename TValue, typename TString>
2507  bool set(TString* key, const TValue& value) {
2508  return set_impl<TString*, const TValue&>(key, value);
2509  }
2510  template <typename TValue, typename TString>
2511  bool set(TString* key, TValue* value) {
2512  return set_impl<TString*, TValue*>(key, value);
2513  }
2514  template <typename TValue, typename TString>
2515  DEPRECATED("Second argument is not supported anymore")
2516  typename Internals::EnableIf<Internals::IsFloatingPoint<TValue>::value,
2517  bool>::type
2518  set(const TString& key, TValue value, uint8_t) {
2519  return set_impl<const TString&, const JsonVariant&>(key,
2520  JsonVariant(value));
2521  }
2522  template <typename TValue, typename TString>
2523  DEPRECATED("Second argument is not supported anymore")
2524  typename Internals::EnableIf<Internals::IsFloatingPoint<TValue>::value,
2525  bool>::type
2526  set(TString* key, TValue value, uint8_t) {
2527  return set_impl<TString*, const JsonVariant&>(key, JsonVariant(value));
2528  }
2529  template <typename TValue, typename TString>
2530  typename Internals::JsonVariantAs<TValue>::type get(
2531  const TString& key) const {
2532  return get_impl<const TString&, TValue>(key);
2533  }
2534  template <typename TValue, typename TString>
2535  typename Internals::JsonVariantAs<TValue>::type get(TString* key) const {
2536  return get_impl<TString*, TValue>(key);
2537  }
2538  template <typename TValue, typename TString>
2539  bool is(const TString& key) const {
2540  return is_impl<const TString&, TValue>(key);
2541  }
2542  template <typename TValue, typename TString>
2543  bool is(TString* key) const {
2544  return is_impl<TString*, TValue>(key);
2545  }
2546  template <typename TString>
2547  JsonArray& createNestedArray(const TString& key) {
2548  return createNestedArray_impl<const TString&>(key);
2549  }
2550  template <typename TString>
2551  JsonArray& createNestedArray(TString* key) {
2552  return createNestedArray_impl<TString*>(key);
2553  }
2554  template <typename TString>
2555  JsonObject& createNestedObject(const TString& key) {
2556  return createNestedObject_impl<const TString&>(key);
2557  }
2558  template <typename TString>
2559  JsonObject& createNestedObject(TString* key) {
2560  return createNestedObject_impl<TString*>(key);
2561  }
2562  template <typename TString>
2563  bool containsKey(const TString& key) const {
2564  return findKey<const TString&>(key) != end();
2565  }
2566  template <typename TString>
2567  bool containsKey(TString* key) const {
2568  return findKey<TString*>(key) != end();
2569  }
2570  template <typename TString>
2571  void remove(const TString& key) {
2572  remove(findKey<const TString&>(key));
2573  }
2574  template <typename TString>
2575  void remove(TString* key) {
2576  remove(findKey<TString*>(key));
2577  }
2578  using Internals::List<JsonPair>::remove;
2579  static JsonObject& invalid() {
2580  static JsonObject instance(NULL);
2581  return instance;
2582  }
2583  private:
2584  template <typename TStringRef>
2585  iterator findKey(TStringRef key) {
2586  iterator it;
2587  for (it = begin(); it != end(); ++it) {
2588  if (Internals::StringTraits<TStringRef>::equals(key, it->key)) break;
2589  }
2590  return it;
2591  }
2592  template <typename TStringRef>
2593  const_iterator findKey(TStringRef key) const {
2594  return const_cast<JsonObject*>(this)->findKey<TStringRef>(key);
2595  }
2596  template <typename TStringRef, typename TValue>
2597  typename Internals::JsonVariantAs<TValue>::type get_impl(
2598  TStringRef key) const {
2599  const_iterator it = findKey<TStringRef>(key);
2600  return it != end() ? it->value.as<TValue>()
2601  : Internals::JsonVariantDefault<TValue>::get();
2602  }
2603  template <typename TStringRef, typename TValueRef>
2604  bool set_impl(TStringRef key, TValueRef value) {
2605  if (Internals::StringTraits<TStringRef>::is_null(key)) return false;
2606  iterator it = findKey<TStringRef>(key);
2607  if (it == end()) {
2608  it = Internals::List<JsonPair>::add();
2609  if (it == end()) return false;
2610  bool key_ok =
2611  Internals::ValueSaver<TStringRef>::save(_buffer, it->key, key);
2612  if (!key_ok) return false;
2613  }
2614  return Internals::ValueSaver<TValueRef>::save(_buffer, it->value, value);
2615  }
2616  template <typename TStringRef, typename TValue>
2617  bool is_impl(TStringRef key) const {
2618  const_iterator it = findKey<TStringRef>(key);
2619  return it != end() ? it->value.is<TValue>() : false;
2620  }
2621  template <typename TStringRef>
2622  JsonArray& createNestedArray_impl(TStringRef key);
2623  template <typename TStringRef>
2624  JsonObject& createNestedObject_impl(TStringRef key);
2625 };
2626 namespace Internals {
2627 template <>
2628 struct JsonVariantDefault<JsonObject> {
2629  static JsonObject& get() {
2630  return JsonObject::invalid();
2631  }
2632 };
2633 } // namespace Internals
2634 } // namespace ArduinoJson
2635 namespace ArduinoJson {
2636 namespace Internals {
2637 class StaticJsonBufferBase : public JsonBufferBase<StaticJsonBufferBase> {
2638  public:
2639  class String {
2640  public:
2641  String(StaticJsonBufferBase* parent) : _parent(parent) {
2642  _start = parent->_buffer + parent->_size;
2643  }
2644  void append(char c) {
2645  if (_parent->canAlloc(1)) {
2646  char* last = static_cast<char*>(_parent->doAlloc(1));
2647  *last = c;
2648  }
2649  }
2650  const char* c_str() const {
2651  if (_parent->canAlloc(1)) {
2652  char* last = static_cast<char*>(_parent->doAlloc(1));
2653  *last = '\0';
2654  return _start;
2655  } else {
2656  return NULL;
2657  }
2658  }
2659  private:
2660  StaticJsonBufferBase* _parent;
2661  char* _start;
2662  };
2663  StaticJsonBufferBase(char* buffer, size_t capa)
2664  : _buffer(buffer), _capacity(capa), _size(0) {}
2665  size_t capacity() const {
2666  return _capacity;
2667  }
2668  size_t size() const {
2669  return _size;
2670  }
2671  virtual void* alloc(size_t bytes) {
2672  alignNextAlloc();
2673  if (!canAlloc(bytes)) return NULL;
2674  return doAlloc(bytes);
2675  }
2676  void clear() {
2677  _size = 0;
2678  }
2679  String startString() {
2680  return String(this);
2681  }
2682  protected:
2683  ~StaticJsonBufferBase() {}
2684  private:
2685  void alignNextAlloc() {
2686  _size = round_size_up(_size);
2687  }
2688  bool canAlloc(size_t bytes) const {
2689  return _size + bytes <= _capacity;
2690  }
2691  void* doAlloc(size_t bytes) {
2692  void* p = &_buffer[_size];
2693  _size += bytes;
2694  return p;
2695  }
2696  char* _buffer;
2697  size_t _capacity;
2698  size_t _size;
2699 };
2700 }
2701 #if defined(__clang__)
2702 #pragma clang diagnostic push
2703 #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
2704 #elif defined(__GNUC__)
2705 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
2706 #pragma GCC diagnostic push
2707 #endif
2708 #pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
2709 #endif
2710 template <size_t CAPACITY>
2711 class StaticJsonBuffer : public Internals::StaticJsonBufferBase {
2712  public:
2713  explicit StaticJsonBuffer()
2714  : Internals::StaticJsonBufferBase(_buffer, CAPACITY) {}
2715  private:
2716  char _buffer[CAPACITY];
2717 };
2718 }
2719 #if defined(__clang__)
2720 #pragma clang diagnostic pop
2721 #elif defined(__GNUC__)
2722 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
2723 #pragma GCC diagnostic pop
2724 #endif
2725 #endif
2726 namespace ArduinoJson {
2727 namespace Internals {
2728 template <typename TInput>
2729 void skipSpacesAndComments(TInput& input) {
2730  for (;;) {
2731  switch (input.current()) {
2732  case ' ':
2733  case '\t':
2734  case '\r':
2735  case '\n':
2736  input.move();
2737  continue;
2738  case '/':
2739  switch (input.next()) {
2740  case '*':
2741  input.move(); // skip '/'
2742  for (;;) {
2743  input.move();
2744  if (input.current() == '\0') return;
2745  if (input.current() == '*' && input.next() == '/') {
2746  input.move(); // skip '*'
2747  input.move(); // skip '/'
2748  break;
2749  }
2750  }
2751  break;
2752  case '/':
2753  for (;;) {
2754  input.move();
2755  if (input.current() == '\0') return;
2756  if (input.current() == '\n') break;
2757  }
2758  break;
2759  default:
2760  return;
2761  }
2762  break;
2763  default:
2764  return;
2765  }
2766  }
2767 }
2768 }
2769 }
2770 template <typename TReader, typename TWriter>
2771 inline bool ArduinoJson::Internals::JsonParser<TReader, TWriter>::eat(
2772  TReader &reader, char charToSkip) {
2773  skipSpacesAndComments(reader);
2774  if (reader.current() != charToSkip) return false;
2775  reader.move();
2776  return true;
2777 }
2778 template <typename TReader, typename TWriter>
2779 inline bool
2780 ArduinoJson::Internals::JsonParser<TReader, TWriter>::parseAnythingTo(
2781  JsonVariant *destination) {
2782  skipSpacesAndComments(_reader);
2783  switch (_reader.current()) {
2784  case '[':
2785  return parseArrayTo(destination);
2786  case '{':
2787  return parseObjectTo(destination);
2788  default:
2789  return parseStringTo(destination);
2790  }
2791 }
2792 template <typename TReader, typename TWriter>
2793 inline ArduinoJson::JsonArray &
2794 ArduinoJson::Internals::JsonParser<TReader, TWriter>::parseArray() {
2795  if (_nestingLimit == 0) return JsonArray::invalid();
2796  _nestingLimit--;
2797  JsonArray &array = _buffer->createArray();
2798  if (!eat('[')) goto ERROR_MISSING_BRACKET;
2799  if (eat(']')) goto SUCCESS_EMPTY_ARRAY;
2800  for (;;) {
2801  JsonVariant value;
2802  if (!parseAnythingTo(&value)) goto ERROR_INVALID_VALUE;
2803  if (!array.add(value)) goto ERROR_NO_MEMORY;
2804  if (eat(']')) goto SUCCES_NON_EMPTY_ARRAY;
2805  if (!eat(',')) goto ERROR_MISSING_COMMA;
2806  }
2807 SUCCESS_EMPTY_ARRAY:
2808 SUCCES_NON_EMPTY_ARRAY:
2809  _nestingLimit++;
2810  return array;
2811 ERROR_INVALID_VALUE:
2812 ERROR_MISSING_BRACKET:
2813 ERROR_MISSING_COMMA:
2814 ERROR_NO_MEMORY:
2815  return JsonArray::invalid();
2816 }
2817 template <typename TReader, typename TWriter>
2818 inline bool ArduinoJson::Internals::JsonParser<TReader, TWriter>::parseArrayTo(
2819  JsonVariant *destination) {
2820  JsonArray &array = parseArray();
2821  if (!array.success()) return false;
2822  *destination = array;
2823  return true;
2824 }
2825 template <typename TReader, typename TWriter>
2826 inline ArduinoJson::JsonObject &
2827 ArduinoJson::Internals::JsonParser<TReader, TWriter>::parseObject() {
2828  if (_nestingLimit == 0) return JsonObject::invalid();
2829  _nestingLimit--;
2830  JsonObject &object = _buffer->createObject();
2831  if (!eat('{')) goto ERROR_MISSING_BRACE;
2832  if (eat('}')) goto SUCCESS_EMPTY_OBJECT;
2833  for (;;) {
2834  const char *key = parseString();
2835  if (!key) goto ERROR_INVALID_KEY;
2836  if (!eat(':')) goto ERROR_MISSING_COLON;
2837  JsonVariant value;
2838  if (!parseAnythingTo(&value)) goto ERROR_INVALID_VALUE;
2839  if (!object.set(key, value)) goto ERROR_NO_MEMORY;
2840  if (eat('}')) goto SUCCESS_NON_EMPTY_OBJECT;
2841  if (!eat(',')) goto ERROR_MISSING_COMMA;
2842  }
2843 SUCCESS_EMPTY_OBJECT:
2844 SUCCESS_NON_EMPTY_OBJECT:
2845  _nestingLimit++;
2846  return object;
2847 ERROR_INVALID_KEY:
2848 ERROR_INVALID_VALUE:
2849 ERROR_MISSING_BRACE:
2850 ERROR_MISSING_COLON:
2851 ERROR_MISSING_COMMA:
2852 ERROR_NO_MEMORY:
2853  return JsonObject::invalid();
2854 }
2855 template <typename TReader, typename TWriter>
2856 inline bool ArduinoJson::Internals::JsonParser<TReader, TWriter>::parseObjectTo(
2857  JsonVariant *destination) {
2858  JsonObject &object = parseObject();
2859  if (!object.success()) return false;
2860  *destination = object;
2861  return true;
2862 }
2863 template <typename TReader, typename TWriter>
2864 inline const char *
2865 ArduinoJson::Internals::JsonParser<TReader, TWriter>::parseString() {
2866  typename RemoveReference<TWriter>::type::String str = _writer.startString();
2867  skipSpacesAndComments(_reader);
2868  char c = _reader.current();
2869  if (isQuote(c)) { // quotes
2870  _reader.move();
2871  char stopChar = c;
2872  for (;;) {
2873  c = _reader.current();
2874  if (c == '\0') break;
2875  _reader.move();
2876  if (c == stopChar) break;
2877  if (c == '\\') {
2878  c = Encoding::unescapeChar(_reader.current());
2879  if (c == '\0') break;
2880  _reader.move();
2881  }
2882  str.append(c);
2883  }
2884  } else { // no quotes
2885  for (;;) {
2886  if (!canBeInNonQuotedString(c)) break;
2887  _reader.move();
2888  str.append(c);
2889  c = _reader.current();
2890  }
2891  }
2892  return str.c_str();
2893 }
2894 template <typename TReader, typename TWriter>
2895 inline bool ArduinoJson::Internals::JsonParser<TReader, TWriter>::parseStringTo(
2896  JsonVariant *destination) {
2897  bool hasQuotes = isQuote(_reader.current());
2898  const char *value = parseString();
2899  if (value == NULL) return false;
2900  if (hasQuotes) {
2901  *destination = value;
2902  } else {
2903  *destination = RawJson(value);
2904  }
2905  return true;
2906 }
2907 #ifdef _MSC_VER
2908 #pragma warning(push)
2909 #pragma warning(disable : 4522)
2910 #endif
2911 namespace ArduinoJson {
2912 namespace Internals {
2913 class JsonArraySubscript : public JsonVariantBase<JsonArraySubscript> {
2914  public:
2915  FORCE_INLINE JsonArraySubscript(JsonArray& array, size_t index)
2916  : _array(array), _index(index) {}
2917  FORCE_INLINE JsonArraySubscript& operator=(const JsonArraySubscript& src) {
2918  _array.set(_index, src);
2919  return *this;
2920  }
2921  template <typename T>
2922  FORCE_INLINE JsonArraySubscript& operator=(const T& src) {
2923  _array.set(_index, src);
2924  return *this;
2925  }
2926  template <typename T>
2927  FORCE_INLINE JsonArraySubscript& operator=(T* src) {
2928  _array.set(_index, src);
2929  return *this;
2930  }
2931  FORCE_INLINE bool success() const {
2932  return _index < _array.size();
2933  }
2934  template <typename T>
2935  FORCE_INLINE typename JsonVariantAs<T>::type as() const {
2936  return _array.get<T>(_index);
2937  }
2938  template <typename T>
2939  FORCE_INLINE bool is() const {
2940  return _array.is<T>(_index);
2941  }
2942  template <typename TValue>
2943  FORCE_INLINE bool set(const TValue& value) {
2944  return _array.set(_index, value);
2945  }
2946  template <typename TValue>
2947  FORCE_INLINE bool set(TValue* value) {
2948  return _array.set(_index, value);
2949  }
2950  template <typename TValue>
2951  DEPRECATED("Second argument is not supported anymore")
2952  FORCE_INLINE bool set(const TValue& value, uint8_t) {
2953  return _array.set(_index, value);
2954  }
2955  private:
2956  JsonArray& _array;
2957  const size_t _index;
2958 };
2959 template <typename TImpl>
2960 inline JsonArraySubscript JsonVariantSubscripts<TImpl>::operator[](
2961  size_t index) {
2962  return impl()->template as<JsonArray>()[index];
2963 }
2964 template <typename TImpl>
2965 inline const JsonArraySubscript JsonVariantSubscripts<TImpl>::operator[](
2966  size_t index) const {
2967  return impl()->template as<JsonArray>()[index];
2968 }
2969 #if ARDUINOJSON_ENABLE_STD_STREAM
2970 inline std::ostream& operator<<(std::ostream& os,
2971  const JsonArraySubscript& source) {
2972  return source.printTo(os);
2973 }
2974 #endif
2975 }
2976 inline Internals::JsonArraySubscript JsonArray::operator[](size_t index) {
2977  return Internals::JsonArraySubscript(*this, index);
2978 }
2979 inline const Internals::JsonArraySubscript JsonArray::operator[](
2980  size_t index) const {
2981  return Internals::JsonArraySubscript(*const_cast<JsonArray*>(this), index);
2982 }
2983 }
2984 #ifdef _MSC_VER
2985 #pragma warning(pop)
2986 #endif
2987 namespace ArduinoJson {
2988 inline JsonArray &JsonArray::createNestedArray() {
2989  if (!_buffer) return JsonArray::invalid();
2990  JsonArray &array = _buffer->createArray();
2991  add(array);
2992  return array;
2993 }
2994 inline JsonObject &JsonArray::createNestedObject() {
2995  if (!_buffer) return JsonObject::invalid();
2996  JsonObject &object = _buffer->createObject();
2997  add(object);
2998  return object;
2999 }
3000 }
3001 inline ArduinoJson::JsonArray &ArduinoJson::JsonBuffer::createArray() {
3002  JsonArray *ptr = new (this) JsonArray(this);
3003  return ptr ? *ptr : JsonArray::invalid();
3004 }
3005 inline ArduinoJson::JsonObject &ArduinoJson::JsonBuffer::createObject() {
3006  JsonObject *ptr = new (this) JsonObject(this);
3007  return ptr ? *ptr : JsonObject::invalid();
3008 }
3009 #ifdef _MSC_VER
3010 #pragma warning(push)
3011 #pragma warning(disable : 4522)
3012 #endif
3013 namespace ArduinoJson {
3014 namespace Internals {
3015 template <typename TStringRef>
3016 class JsonObjectSubscript
3017  : public JsonVariantBase<JsonObjectSubscript<TStringRef> > {
3018  typedef JsonObjectSubscript<TStringRef> this_type;
3019  public:
3020  FORCE_INLINE JsonObjectSubscript(JsonObject& object, TStringRef key)
3021  : _object(object), _key(key) {}
3022  FORCE_INLINE this_type& operator=(const this_type& src) {
3023  _object.set(_key, src);
3024  return *this;
3025  }
3026  template <typename TValue>
3027  FORCE_INLINE typename EnableIf<!IsArray<TValue>::value, this_type&>::type
3028  operator=(const TValue& src) {
3029  _object.set(_key, src);
3030  return *this;
3031  }
3032  template <typename TValue>
3033  FORCE_INLINE this_type& operator=(TValue* src) {
3034  _object.set(_key, src);
3035  return *this;
3036  }
3037  FORCE_INLINE bool success() const {
3038  return _object.containsKey(_key);
3039  }
3040  template <typename TValue>
3041  FORCE_INLINE typename JsonVariantAs<TValue>::type as() const {
3042  return _object.get<TValue>(_key);
3043  }
3044  template <typename TValue>
3045  FORCE_INLINE bool is() const {
3046  return _object.is<TValue>(_key);
3047  }
3048  template <typename TValue>
3049  FORCE_INLINE typename EnableIf<!IsArray<TValue>::value, bool>::type set(
3050  const TValue& value) {
3051  return _object.set(_key, value);
3052  }
3053  template <typename TValue>
3054  FORCE_INLINE bool set(const TValue* value) {
3055  return _object.set(_key, value);
3056  }
3057  template <typename TValue>
3058  DEPRECATED("Second argument is not supported anymore")
3059  FORCE_INLINE bool set(const TValue& value, uint8_t) {
3060  return _object.set(_key, value);
3061  }
3062  private:
3063  JsonObject& _object;
3064  TStringRef _key;
3065 };
3066 #if ARDUINOJSON_ENABLE_STD_STREAM
3067 template <typename TStringRef>
3068 inline std::ostream& operator<<(std::ostream& os,
3069  const JsonObjectSubscript<TStringRef>& source) {
3070  return source.printTo(os);
3071 }
3072 #endif
3073 }
3074 }
3075 #ifdef _MSC_VER
3076 #pragma warning(pop)
3077 #endif
3078 namespace ArduinoJson {
3079 template <typename TStringRef>
3080 inline JsonArray &JsonObject::createNestedArray_impl(TStringRef key) {
3081  if (!_buffer) return JsonArray::invalid();
3082  JsonArray &array = _buffer->createArray();
3083  set(key, array);
3084  return array;
3085 }
3086 template <typename TStringRef>
3087 inline JsonObject &JsonObject::createNestedObject_impl(TStringRef key) {
3088  if (!_buffer) return JsonObject::invalid();
3089  JsonObject &object = _buffer->createObject();
3090  set(key, object);
3091  return object;
3092 }
3093 }
3094 namespace ArduinoJson {
3095 namespace Internals {
3096 inline bool isdigit(char c) {
3097  return '0' <= c && c <= '9';
3098 }
3099 inline bool issign(char c) {
3100  return '-' == c || c == '+';
3101 }
3102 }
3103 }
3104 namespace ArduinoJson {
3105 namespace Internals {
3106 inline bool isFloat(const char* s) {
3107  if (!s) return false;
3108  if (!strcmp(s, "NaN")) return true;
3109  if (issign(*s)) s++;
3110  if (!strcmp(s, "Infinity")) return true;
3111  if (*s == '\0') return false;
3112  while (isdigit(*s)) s++;
3113  if (*s == '.') {
3114  s++;
3115  while (isdigit(*s)) s++;
3116  }
3117  if (*s == 'e' || *s == 'E') {
3118  s++;
3119  if (issign(*s)) s++;
3120  if (!isdigit(*s)) return false;
3121  while (isdigit(*s)) s++;
3122  }
3123  return *s == '\0';
3124 }
3125 }
3126 }
3127 namespace ArduinoJson {
3128 namespace Internals {
3129 inline bool isInteger(const char* s) {
3130  if (!s || !*s) return false;
3131  if (issign(*s)) s++;
3132  while (isdigit(*s)) s++;
3133  return *s == '\0';
3134 }
3135 } // namespace Internals
3136 } // namespace ArduinoJson
3137 namespace ArduinoJson {
3138 namespace Internals {
3139 template <typename T>
3140 inline T parseFloat(const char* s) {
3141  typedef FloatTraits<T> traits;
3142  typedef typename traits::mantissa_type mantissa_t;
3143  typedef typename traits::exponent_type exponent_t;
3144  if (!s) return 0; // NULL
3145  bool negative_result = false;
3146  switch (*s) {
3147  case '-':
3148  negative_result = true;
3149  s++;
3150  break;
3151  case '+':
3152  s++;
3153  break;
3154  }
3155  if (*s == 't') return 1; // true
3156  if (*s == 'n' || *s == 'N') return traits::nan();
3157  if (*s == 'i' || *s == 'I')
3158  return negative_result ? -traits::inf() : traits::inf();
3159  mantissa_t mantissa = 0;
3160  exponent_t exponent_offset = 0;
3161  while (isdigit(*s)) {
3162  if (mantissa < traits::mantissa_max / 10)
3163  mantissa = mantissa * 10 + (*s - '0');
3164  else
3165  exponent_offset++;
3166  s++;
3167  }
3168  if (*s == '.') {
3169  s++;
3170  while (isdigit(*s)) {
3171  if (mantissa < traits::mantissa_max / 10) {
3172  mantissa = mantissa * 10 + (*s - '0');
3173  exponent_offset--;
3174  }
3175  s++;
3176  }
3177  }
3178  int exponent = 0;
3179  if (*s == 'e' || *s == 'E') {
3180  s++;
3181  bool negative_exponent = false;
3182  if (*s == '-') {
3183  negative_exponent = true;
3184  s++;
3185  } else if (*s == '+') {
3186  s++;
3187  }
3188  while (isdigit(*s)) {
3189  exponent = exponent * 10 + (*s - '0');
3190  if (exponent + exponent_offset > traits::exponent_max) {
3191  if (negative_exponent)
3192  return negative_result ? -0.0f : 0.0f;
3193  else
3194  return negative_result ? -traits::inf() : traits::inf();
3195  }
3196  s++;
3197  }
3198  if (negative_exponent) exponent = -exponent;
3199  }
3200  exponent += exponent_offset;
3201  T result = traits::make_float(static_cast<T>(mantissa), exponent);
3202  return negative_result ? -result : result;
3203 }
3204 }
3205 }
3206 namespace ArduinoJson {
3207 namespace Internals {
3208 template <typename T>
3209 T parseInteger(const char *s) {
3210  if (!s) return 0; // NULL
3211  if (*s == 't') return 1; // "true"
3212  T result = 0;
3213  bool negative_result = false;
3214  switch (*s) {
3215  case '-':
3216  negative_result = true;
3217  s++;
3218  break;
3219  case '+':
3220  s++;
3221  break;
3222  }
3223  while (isdigit(*s)) {
3224  result = T(result * 10 + T(*s - '0'));
3225  s++;
3226  }
3227  return negative_result ? T(~result + 1) : result;
3228 }
3229 }
3230 }
3231 namespace ArduinoJson {
3232 inline JsonVariant::JsonVariant(const JsonArray &array) {
3233  if (array.success()) {
3234  _type = Internals::JSON_ARRAY;
3235  _content.asArray = const_cast<JsonArray *>(&array);
3236  } else {
3237  _type = Internals::JSON_UNDEFINED;
3238  }
3239 }
3240 inline JsonVariant::JsonVariant(const JsonObject &object) {
3241  if (object.success()) {
3242  _type = Internals::JSON_OBJECT;
3243  _content.asObject = const_cast<JsonObject *>(&object);
3244  } else {
3245  _type = Internals::JSON_UNDEFINED;
3246  }
3247 }
3248 inline JsonArray &JsonVariant::variantAsArray() const {
3249  if (_type == Internals::JSON_ARRAY) return *_content.asArray;
3250  return JsonArray::invalid();
3251 }
3252 inline JsonObject &JsonVariant::variantAsObject() const {
3253  if (_type == Internals::JSON_OBJECT) return *_content.asObject;
3254  return JsonObject::invalid();
3255 }
3256 template <typename T>
3257 inline T JsonVariant::variantAsInteger() const {
3258  using namespace Internals;
3259  switch (_type) {
3260  case JSON_UNDEFINED:
3261  return 0;
3262  case JSON_POSITIVE_INTEGER:
3263  case JSON_BOOLEAN:
3264  return T(_content.asInteger);
3265  case JSON_NEGATIVE_INTEGER:
3266  return T(~_content.asInteger + 1);
3267  case JSON_STRING:
3268  case JSON_UNPARSED:
3269  return parseInteger<T>(_content.asString);
3270  default:
3271  return T(_content.asFloat);
3272  }
3273 }
3274 inline const char *JsonVariant::variantAsString() const {
3275  using namespace Internals;
3276  if (_type == JSON_UNPARSED && _content.asString &&
3277  !strcmp("null", _content.asString))
3278  return NULL;
3279  if (_type == JSON_STRING || _type == JSON_UNPARSED) return _content.asString;
3280  return NULL;
3281 }
3282 template <typename T>
3283 inline T JsonVariant::variantAsFloat() const {
3284  using namespace Internals;
3285  switch (_type) {
3286  case JSON_UNDEFINED:
3287  return 0;
3288  case JSON_POSITIVE_INTEGER:
3289  case JSON_BOOLEAN:
3290  return static_cast<T>(_content.asInteger);
3291  case JSON_NEGATIVE_INTEGER:
3292  return -static_cast<T>(_content.asInteger);
3293  case JSON_STRING:
3294  case JSON_UNPARSED:
3295  return parseFloat<T>(_content.asString);
3296  default:
3297  return static_cast<T>(_content.asFloat);
3298  }
3299 }
3300 inline bool JsonVariant::variantIsBoolean() const {
3301  using namespace Internals;
3302  if (_type == JSON_BOOLEAN) return true;
3303  if (_type != JSON_UNPARSED || _content.asString == NULL) return false;
3304  return !strcmp(_content.asString, "true") ||
3305  !strcmp(_content.asString, "false");
3306 }
3307 inline bool JsonVariant::variantIsInteger() const {
3308  using namespace Internals;
3309  return _type == JSON_POSITIVE_INTEGER || _type == JSON_NEGATIVE_INTEGER ||
3310  (_type == JSON_UNPARSED && isInteger(_content.asString));
3311 }
3312 inline bool JsonVariant::variantIsFloat() const {
3313  using namespace Internals;
3314  return _type == JSON_FLOAT || _type == JSON_POSITIVE_INTEGER ||
3315  _type == JSON_NEGATIVE_INTEGER ||
3316  (_type == JSON_UNPARSED && isFloat(_content.asString));
3317 }
3318 #if ARDUINOJSON_ENABLE_STD_STREAM
3319 inline std::ostream &operator<<(std::ostream &os, const JsonVariant &source) {
3320  return source.printTo(os);
3321 }
3322 #endif
3323 } // namespace ArduinoJson
3324 template <typename Writer>
3325 inline void ArduinoJson::Internals::JsonSerializer<Writer>::serialize(
3326  const JsonArray& array, Writer& writer) {
3327  writer.beginArray();
3328  JsonArray::const_iterator it = array.begin();
3329  while (it != array.end()) {
3330  serialize(*it, writer);
3331  ++it;
3332  if (it == array.end()) break;
3333  writer.writeComma();
3334  }
3335  writer.endArray();
3336 }
3337 template <typename Writer>
3338 inline void ArduinoJson::Internals::JsonSerializer<Writer>::serialize(
3339  const JsonArraySubscript& arraySubscript, Writer& writer) {
3340  serialize(arraySubscript.as<JsonVariant>(), writer);
3341 }
3342 template <typename Writer>
3343 inline void ArduinoJson::Internals::JsonSerializer<Writer>::serialize(
3344  const JsonObject& object, Writer& writer) {
3345  writer.beginObject();
3346  JsonObject::const_iterator it = object.begin();
3347  while (it != object.end()) {
3348  writer.writeString(it->key);
3349  writer.writeColon();
3350  serialize(it->value, writer);
3351  ++it;
3352  if (it == object.end()) break;
3353  writer.writeComma();
3354  }
3355  writer.endObject();
3356 }
3357 template <typename Writer>
3358 template <typename TKey>
3359 inline void ArduinoJson::Internals::JsonSerializer<Writer>::serialize(
3360  const JsonObjectSubscript<TKey>& objectSubscript, Writer& writer) {
3361  serialize(objectSubscript.template as<JsonVariant>(), writer);
3362 }
3363 template <typename Writer>
3364 inline void ArduinoJson::Internals::JsonSerializer<Writer>::serialize(
3365  const JsonVariant& variant, Writer& writer) {
3366  switch (variant._type) {
3367  case JSON_FLOAT:
3368  writer.writeFloat(variant._content.asFloat);
3369  return;
3370  case JSON_ARRAY:
3371  serialize(*variant._content.asArray, writer);
3372  return;
3373  case JSON_OBJECT:
3374  serialize(*variant._content.asObject, writer);
3375  return;
3376  case JSON_STRING:
3377  writer.writeString(variant._content.asString);
3378  return;
3379  case JSON_UNPARSED:
3380  writer.writeRaw(variant._content.asString);
3381  return;
3382  case JSON_NEGATIVE_INTEGER:
3383  writer.writeRaw('-'); // Falls through.
3384  case JSON_POSITIVE_INTEGER:
3385  writer.writeInteger(variant._content.asInteger);
3386  return;
3387  case JSON_BOOLEAN:
3388  writer.writeBoolean(variant._content.asInteger != 0);
3389  return;
3390  default: // JSON_UNDEFINED
3391  return;
3392  }
3393 }
3394 
3395 using namespace ArduinoJson;
3396 
3397 #else
3398 
3399 #error ArduinoJson requires a C++ compiler, please change file extension to .cc or .cpp
3400 
3401 #endif