From fead9b50b1f9ae3a9487cb67724f69e4dd7323a9 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Fri, 31 Oct 2014 21:08:04 +0100 Subject: [PATCH] Fixed bug in parser when "null", "true" or "false" is mispelled --- include/ArduinoJson/Internals/JsonParser.hpp | 1 + src/Internals/JsonParser.cpp | 27 ++++++++++++-------- test/JsonParser_Array_Tests.cpp | 15 +++++++++++ 3 files changed, 33 insertions(+), 10 deletions(-) diff --git a/include/ArduinoJson/Internals/JsonParser.hpp b/include/ArduinoJson/Internals/JsonParser.hpp index b423978a..be21b385 100644 --- a/include/ArduinoJson/Internals/JsonParser.hpp +++ b/include/ArduinoJson/Internals/JsonParser.hpp @@ -22,6 +22,7 @@ class JsonParser { bool isEnd() { return *_ptr == '\0'; } bool skip(char charToSkip); + bool skip(const char *wordToSkip); void skipSpaces(); void parseAnythingTo(JsonValue &destination); diff --git a/src/Internals/JsonParser.cpp b/src/Internals/JsonParser.cpp index de736c02..d7fe1fb0 100644 --- a/src/Internals/JsonParser.cpp +++ b/src/Internals/JsonParser.cpp @@ -30,6 +30,15 @@ bool JsonParser::skip(char charToSkip) { return true; } +bool JsonParser::skip(const char *wordToSkip) { + const char *charToSkip = wordToSkip; + while (*charToSkip && *_ptr == *charToSkip) { + charToSkip++; + _ptr++; + } + return *charToSkip == '\0'; +} + void JsonParser::parseAnythingTo(JsonValue &destination) { skipSpaces(); @@ -96,13 +105,10 @@ JsonArray &JsonParser::parseArray() { void JsonParser::parseBooleanTo(JsonValue &destination) { bool value = *_ptr == 't'; - // TODO: bug if string ends here !!! - - _ptr += value ? 4 : 5; - // 4 = strlen("true") - // 5 = strlen("false"); - - destination = value; + if (skip(value ? "true" : "false")) + destination = value; + else + destination = JsonValue::invalid(); } void JsonParser::parseNumberTo(JsonValue &destination) { @@ -121,9 +127,10 @@ void JsonParser::parseNumberTo(JsonValue &destination) { } void JsonParser::parseNullTo(JsonValue &destination) { - _ptr += 4; // strlen("null") - - destination = static_cast(NULL); + if (skip("null")) + destination = static_cast(NULL); + else + destination = JsonValue::invalid(); } JsonObject &JsonParser::parseObject() { diff --git a/test/JsonParser_Array_Tests.cpp b/test/JsonParser_Array_Tests.cpp index c4ba4922..64f8b889 100644 --- a/test/JsonParser_Array_Tests.cpp +++ b/test/JsonParser_Array_Tests.cpp @@ -143,6 +143,21 @@ TEST_F(JsonParser_Array_Tests, TwoNulls) { secondElementMustBe(nullCharPtr); } +TEST_F(JsonParser_Array_Tests, IncompleteNull) { + whenInputIs("[nul!]"); + parseMustFail(); +} + +TEST_F(JsonParser_Array_Tests, IncompleteTrue) { + whenInputIs("[tru!]"); + parseMustFail(); +} + +TEST_F(JsonParser_Array_Tests, IncompleteFalse) { + whenInputIs("[fals!]"); + parseMustFail(); +} + TEST_F(JsonParser_Array_Tests, TwoStrings) { whenInputIs("[\"hello\",\"world\"]");