Files
ArduinoJson/JsonGenerator/JsonPrettyPrint.cpp

97 lines
1.8 KiB
C++
Raw Normal View History

/*
* Arduino JSON library
* Benoit Blanchon 2014 - MIT License
*/
#include "JsonPrettyPrint.h"
using namespace ArduinoJson::Generator;
size_t JsonPrettyPrint::write(uint8_t c)
{
2014-08-25 12:41:49 +02:00
size_t n = inString ? handleStringChar(c) : handleMarkupChar(c);
previousChar = c;
return n;
}
size_t JsonPrettyPrint::handleStringChar(uint8_t c)
2014-08-25 12:41:49 +02:00
{
bool isQuote = c == '"' && previousChar != '\\';
2014-08-25 11:46:42 +02:00
2014-08-25 12:48:38 +02:00
if (isQuote) inString = false;
2014-08-26 09:49:59 +02:00
return sink.write(c);
2014-08-25 12:41:49 +02:00
}
size_t JsonPrettyPrint::handleMarkupChar(uint8_t c)
2014-08-25 12:41:49 +02:00
{
2014-08-25 09:52:42 +02:00
switch (c)
{
case '{':
case '[':
2014-08-25 13:14:09 +02:00
return handleBlockOpen(c);
2014-08-25 09:52:42 +02:00
case '}':
2014-08-25 12:41:49 +02:00
case ']':
2014-08-25 13:14:09 +02:00
return handleBlockClose(c);
case ':':
2014-08-25 13:14:09 +02:00
return handleColumn();
case ',':
return handleComma();
2014-08-25 10:22:42 +02:00
2014-08-25 12:41:49 +02:00
case '"':
2014-08-25 13:14:09 +02:00
return handleQuoteOpen();
2014-08-25 11:46:42 +02:00
default:
2014-08-25 13:14:09 +02:00
return handleNormalChar(c);
2014-08-25 09:52:42 +02:00
}
}
size_t JsonPrettyPrint::handleBlockOpen(uint8_t c)
{
2014-08-26 09:49:59 +02:00
return indentIfNeeded() + sink.write(c);
}
size_t JsonPrettyPrint::handleBlockClose(uint8_t c)
{
2014-08-26 09:49:59 +02:00
return unindentIfNeeded() + sink.write(c);
}
size_t JsonPrettyPrint::handleColumn()
{
2014-08-26 09:49:59 +02:00
return sink.write(':') + sink.write(' ');
}
size_t JsonPrettyPrint::handleComma()
{
2014-08-26 09:49:59 +02:00
return sink.write(',') + sink.println();
}
size_t JsonPrettyPrint::handleQuoteOpen()
2014-08-25 12:41:49 +02:00
{
2014-08-25 12:48:38 +02:00
inString = true;
2014-08-26 09:49:59 +02:00
return indentIfNeeded() + sink.write('"');
2014-08-25 12:41:49 +02:00
}
size_t JsonPrettyPrint::handleNormalChar(uint8_t c)
{
2014-08-26 09:49:59 +02:00
return indentIfNeeded() + sink.write(c);
2014-08-25 12:41:49 +02:00
}
size_t JsonPrettyPrint::indentIfNeeded()
2014-08-25 12:41:49 +02:00
{
if (!inEmptyBlock()) return 0;
2014-08-25 12:41:49 +02:00
sink.indent();
return sink.println();
2014-08-26 09:49:59 +02:00
}
size_t JsonPrettyPrint::unindentIfNeeded()
2014-08-26 09:49:59 +02:00
{
if (inEmptyBlock()) return 0;
sink.unindent();
return sink.println();
}