Fixed bug in parser when "null", "true" or "false" is mispelled

This commit is contained in:
Benoit Blanchon
2014-10-31 21:08:04 +01:00
parent 98463ea168
commit fead9b50b1
3 changed files with 33 additions and 10 deletions

View File

@ -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);

View File

@ -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<const char *>(NULL);
if (skip("null"))
destination = static_cast<const char *>(NULL);
else
destination = JsonValue::invalid();
}
JsonObject &JsonParser::parseObject() {

View File

@ -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\"]");