Skip to content

Commit

Permalink
json: Support parsing true, false, and null
Browse files Browse the repository at this point in the history
  • Loading branch information
robinlinden committed Jan 13, 2025
1 parent 0ea71b7 commit a593af4
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
43 changes: 43 additions & 0 deletions json/json.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,54 @@ class Parser {
switch (*c) {
case '"':
return parse_string();
case 't':
return parse_true();
case 'f':
return parse_false();
case 'n':
return parse_null();
default:
return std::nullopt;
}
}

constexpr std::optional<Value> parse_true() {
std::ignore = consume(); // 't'
auto r = consume();
auto u = consume();
auto e = consume();
if (r != 'r' || u != 'u' || e != 'e') {
return std::nullopt;
}

return Value{true};
}

constexpr std::optional<Value> parse_false() {
std::ignore = consume(); // 'f'
auto a = consume();
auto l = consume();
auto s = consume();
auto e = consume();
if (a != 'a' || l != 'l' || s != 's' || e != 'e') {
return std::nullopt;
}

return Value{false};
}

constexpr std::optional<Value> parse_null() {
std::ignore = consume(); // 'n'
auto u = consume();
auto l1 = consume();
auto l2 = consume();
if (u != 'u' || l1 != 'l' || l2 != 'l') {
return std::nullopt;
}

return Value{Null{}};
}

constexpr std::optional<Value> parse_string() {
std::string value;
std::ignore = consume(); // '"'
Expand Down
25 changes: 25 additions & 0 deletions json/json_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,30 @@ int main() {
a.expect_eq(json::parse(R"("hello\p")"), std::nullopt);
});

s.add_test("true", [](etest::IActions &a) {
a.expect_eq(json::parse("true"), json::Value{true});
a.expect_eq(json::parse("tru0"), std::nullopt);
a.expect_eq(json::parse("tr00"), std::nullopt);
a.expect_eq(json::parse("t000"), std::nullopt);
a.expect_eq(json::parse("true!"), std::nullopt);
});

s.add_test("false", [](etest::IActions &a) {
a.expect_eq(json::parse("false"), json::Value{false});
a.expect_eq(json::parse("fals0"), std::nullopt);
a.expect_eq(json::parse("fal00"), std::nullopt);
a.expect_eq(json::parse("fa000"), std::nullopt);
a.expect_eq(json::parse("f0000"), std::nullopt);
a.expect_eq(json::parse("false!"), std::nullopt);
});

s.add_test("null", [](etest::IActions &a) {
a.expect_eq(json::parse("null"), json::Value{json::Null{}});
a.expect_eq(json::parse("nul0"), std::nullopt);
a.expect_eq(json::parse("nu00"), std::nullopt);
a.expect_eq(json::parse("n000"), std::nullopt);
a.expect_eq(json::parse("null!"), std::nullopt);
});

return s.run();
}

0 comments on commit a593af4

Please sign in to comment.