PrettyPrintDecorator.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Arduino JSON library
  3. * Benoit Blanchon 2014 - MIT License
  4. */
  5. #include "PrettyPrintDecorator.h"
  6. using namespace ArduinoJson::Generator;
  7. size_t PrettyPrintDecorator::write(uint8_t c)
  8. {
  9. size_t n = inString ? handleStringChar(c) : handleMarkupChar(c);
  10. previousChar = c;
  11. return n;
  12. }
  13. size_t PrettyPrintDecorator::handleStringChar(uint8_t c)
  14. {
  15. bool isQuote = c == '"' && previousChar != '\\';
  16. if (isQuote) inString = false;
  17. return writeChar(c);
  18. }
  19. size_t PrettyPrintDecorator::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. size_t PrettyPrintDecorator::handleBlockOpen(uint8_t c)
  40. {
  41. size_t n = inEmptyBlock() ? breakThenWrite(c) : writeChar(c);
  42. indent++;
  43. return n;
  44. }
  45. size_t PrettyPrintDecorator::handleBlockClose(uint8_t c)
  46. {
  47. indent--;
  48. return inEmptyBlock() ? writeChar(c) : breakThenWrite(c);
  49. }
  50. size_t PrettyPrintDecorator::handleColumn()
  51. {
  52. return writeChar(':') + writeChar(' ');
  53. }
  54. size_t PrettyPrintDecorator::handleComma()
  55. {
  56. return writeThenBreak(',');
  57. }
  58. size_t PrettyPrintDecorator::handleQuoteOpen()
  59. {
  60. size_t n = inEmptyBlock() ? breakThenWrite('"') : writeChar('"');
  61. inString = true;
  62. return n;
  63. }
  64. size_t PrettyPrintDecorator::handleNormalChar(uint8_t c)
  65. {
  66. return inEmptyBlock() ? breakThenWrite(c) : writeChar(c);
  67. }
  68. size_t PrettyPrintDecorator::breakAndIndent()
  69. {
  70. size_t n = writeChar('\n');
  71. for (int i = 0; i < indent; i++)
  72. n += writeChar(' ');
  73. return n;
  74. }