JsonValue.h 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /*
  2. * Arduino JSON library
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #pragma once
  6. #include "EscapedString.h"
  7. #include "Printable.h"
  8. #include "StringBuilder.h"
  9. namespace ArduinoJson
  10. {
  11. namespace Generator
  12. {
  13. class JsonValue
  14. {
  15. public:
  16. void operator=(bool value)
  17. {
  18. _printToImpl = &printBoolTo;
  19. _content.asBool = value;
  20. }
  21. void operator=(long value)
  22. {
  23. _printToImpl = &printLongTo;
  24. _content.asLong = value;
  25. }
  26. void operator=(int value)
  27. {
  28. _printToImpl = &printLongTo;
  29. _content.asLong = value;
  30. }
  31. void operator=(const Printable& value)
  32. {
  33. _printToImpl = &printPrintableTo;
  34. _content.asPrintable = &value;
  35. }
  36. void operator=(const char* value)
  37. {
  38. _printToImpl = &printStringTo;
  39. _content.asString = value;
  40. }
  41. void operator=(double value)
  42. {
  43. set<2>(value);
  44. }
  45. template <int DIGITS>
  46. void set(double value)
  47. {
  48. _printToImpl = &printDoubleTo < DIGITS > ;
  49. _content.asDouble = value;
  50. }
  51. operator bool()
  52. {
  53. return _content.asBool;
  54. }
  55. operator const char*()
  56. {
  57. return _content.asString;
  58. }
  59. operator double()
  60. {
  61. return _content.asDouble;
  62. }
  63. operator float()
  64. {
  65. return static_cast<float>(_content.asDouble);
  66. }
  67. operator int()
  68. {
  69. return _content.asLong;
  70. }
  71. operator long()
  72. {
  73. return _content.asLong;
  74. }
  75. operator const Printable&()
  76. {
  77. return *_content.asPrintable;
  78. }
  79. size_t printTo(Print& p) const
  80. {
  81. // handmade polymorphism
  82. return _printToImpl(_content, p);
  83. }
  84. void reset()
  85. {
  86. _content.asDouble = 0;
  87. _printToImpl = printStringTo;
  88. }
  89. private:
  90. union Content
  91. {
  92. bool asBool;
  93. double asDouble;
  94. long asLong;
  95. const Printable* asPrintable;
  96. const char* asString;
  97. };
  98. Content _content;
  99. size_t(*_printToImpl)(const Content&, Print&);
  100. static size_t printBoolTo(const Content&, Print&);
  101. static size_t printLongTo(const Content&, Print&);
  102. static size_t printPrintableTo(const Content&, Print&);
  103. static size_t printStringTo(const Content&, Print&);
  104. template <int DIGITS>
  105. static size_t printDoubleTo(const Content& c, Print& p)
  106. {
  107. return p.print(c.asDouble, DIGITS);
  108. }
  109. };
  110. }
  111. }