Parser: unescape strings

This commit is contained in:
Benoit Blanchon
2014-10-17 19:57:00 +02:00
parent b15dac7edf
commit 9c32ae2300
4 changed files with 66 additions and 9 deletions

View File

@ -15,6 +15,8 @@ namespace ArduinoJson
{ {
public: public:
static size_t printTo(const char*, Print*); static size_t printTo(const char*, Print*);
static char* extractFrom(char* input, char** end);
}; };
} }
} }

View File

@ -42,4 +42,47 @@ size_t EscapedString::printTo(const char* s, Print* p)
} }
return n + p->write('\"'); return n + p->write('\"');
}
static char unescapeChar(char c)
{
// Optimized for code size on a 8-bit AVR
const char* p = "b\bf\fn\nr\rt\t";
while (true)
{
if (p[0] == 0) return c;
if (p[0] == c) return p[1];
p += 2;
}
}
char* EscapedString::extractFrom(char* input, char** end)
{
char* start = input + 1; // skip quote
char* readPtr = start;
char* writePtr = start;
char c;
do
{
c = *readPtr++;
if (c == '\"')
break;
if (c == '\\')
{
c = unescapeChar(*readPtr++);
}
*writePtr++ = c;
} while (c != 0);
*writePtr = 0;
*end = readPtr;
return start;
} }

View File

@ -1,8 +1,13 @@
#include "ArduinoJson/Internals/JsonParser.h" #include "ArduinoJson/Internals/JsonParser.h"
#include "ArduinoJson/JsonBuffer.h"
#include <stdlib.h> // for strtol, strtod #include <stdlib.h> // for strtol, strtod
#include <ctype.h> #include <ctype.h>
#include "ArduinoJson/JsonBuffer.h"
#include "ArduinoJson/Internals/EscapedString.h"
using namespace ArduinoJson::Internals;
bool JsonParser::isArrayStart() bool JsonParser::isArrayStart()
{ {
return *_ptr == '['; return *_ptr == '[';
@ -179,12 +184,6 @@ JsonNode* JsonParser::parseNull()
JsonNode* JsonParser::parseString() JsonNode* JsonParser::parseString()
{ {
const char* s = ++_ptr; const char* s = EscapedString::extractFrom(_ptr, &_ptr);
while (*_ptr != '\"')
_ptr++;
*_ptr = 0;
_ptr++;
return _buffer->createStringNode(s); return _buffer->createStringNode(s);
} }

View File

@ -21,6 +21,13 @@ protected:
const char* _result; const char* _result;
}; };
TEST_F(JsonParser_String_Tests, EmptyString)
{
whenInputIs("\"\"");
outputMustBe("");
}
TEST_F(JsonParser_String_Tests, SimpleString) TEST_F(JsonParser_String_Tests, SimpleString)
{ {
whenInputIs("\"hello world\""); whenInputIs("\"hello world\"");
@ -39,8 +46,14 @@ TEST_F(JsonParser_String_Tests, SquareBraquets)
outputMustBe("[hello,world]"); outputMustBe("[hello,world]");
} }
TEST_F(JsonParser_String_Tests, EscapedQuote) TEST_F(JsonParser_String_Tests, EscapedDoubleQuote)
{ {
whenInputIs("\"hello \\\"world\\\"\""); whenInputIs("\"hello \\\"world\\\"\"");
outputMustBe("hello \"world\""); outputMustBe("hello \"world\"");
}
TEST_F(JsonParser_String_Tests, EscapedSingleQuote)
{
whenInputIs("\"hello \\\'world\\\'\"");
outputMustBe("hello 'world'");
} }