JsonPrettyPrint.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Arduino JSON library
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #include "JsonPrettyPrint.h"
  6. using namespace ArduinoJson::Generator;
  7. size_t JsonPrettyPrint::write(uint8_t c)
  8. {
  9. size_t n = inString ? handleStringChar(c) : handleMarkupChar(c);
  10. previousChar = c;
  11. return n;
  12. }
  13. inline size_t JsonPrettyPrint::handleStringChar(uint8_t c)
  14. {
  15. bool isQuote = c == '"' && previousChar != '\\';
  16. if (isQuote) inString = false;
  17. return sink.write(c);
  18. }
  19. inline size_t JsonPrettyPrint::handleMarkupChar(uint8_t c)
  20. {
  21. switch (c)
  22. {
  23. case '{':
  24. case '[':
  25. return handleBlockOpen(c);
  26. case '}':
  27. case ']':
  28. return handleBlockClose(c);
  29. case ':':
  30. return handleColumn();
  31. case ',':
  32. return handleComma();
  33. case '"':
  34. return handleQuoteOpen();
  35. default:
  36. return handleNormalChar(c);
  37. }
  38. }
  39. inline size_t JsonPrettyPrint::handleBlockOpen(uint8_t c)
  40. {
  41. return indentIfNeeded() + sink.write(c);
  42. }
  43. inline size_t JsonPrettyPrint::handleBlockClose(uint8_t c)
  44. {
  45. return unindentIfNeeded() + sink.write(c);
  46. }
  47. inline size_t JsonPrettyPrint::handleColumn()
  48. {
  49. return sink.write(':') + sink.write(' ');
  50. }
  51. inline size_t JsonPrettyPrint::handleComma()
  52. {
  53. return sink.write(',') + sink.println();
  54. }
  55. inline size_t JsonPrettyPrint::handleQuoteOpen()
  56. {
  57. inString = true;
  58. return indentIfNeeded() + sink.write('"');
  59. }
  60. inline size_t JsonPrettyPrint::handleNormalChar(uint8_t c)
  61. {
  62. return indentIfNeeded() + sink.write(c);
  63. }
  64. size_t JsonPrettyPrint::indentIfNeeded()
  65. {
  66. if (!inEmptyBlock()) return 0;
  67. sink.indent();
  68. return sink.println();
  69. }
  70. size_t JsonPrettyPrint::unindentIfNeeded()
  71. {
  72. if (inEmptyBlock()) return 0;
  73. sink.unindent();
  74. return sink.println();
  75. }