PrettyPrintDecorator.cpp 1.8 KB

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