diff options
author | Emanuel Sprung <emanuel.sprung@gmail.com> | 2020-03-24 21:59:22 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-03-24 22:20:07 +0100 |
commit | bca57625429fe099df8cbffe24deb11f7536ea1b (patch) | |
tree | ebe0070f217f59c4e1560dc21261e9d9f1a97aa1 /AK/JsonParser.cpp | |
parent | 45921328e4923a49870f6bd770da3bbbc3b60777 (diff) | |
download | serenity-bca57625429fe099df8cbffe24deb11f7536ea1b.zip |
AK: Add parsing of JSON double values
This patch adds the parsing of double values to the JSON parser.
There is another char buffer that get's filled when a "." is present
in the number parsing. When number finished, a divider is calculated
to transform the number behind the "." to the actual fraction value.
Diffstat (limited to 'AK/JsonParser.cpp')
-rw-r--r-- | AK/JsonParser.cpp | 41 |
1 files changed, 36 insertions, 5 deletions
diff --git a/AK/JsonParser.cpp b/AK/JsonParser.cpp index 323a0308f6..c84c35a38d 100644 --- a/AK/JsonParser.cpp +++ b/AK/JsonParser.cpp @@ -191,10 +191,21 @@ JsonValue JsonParser::parse_string() JsonValue JsonParser::parse_number() { Vector<char, 128> number_buffer; + Vector<char, 128> fraction_buffer; + + bool is_double = false; for (;;) { char ch = peek(); + if (ch == '.') { + is_double = true; + ++m_index; + continue; + } if (ch == '-' || (ch >= '0' && ch <= '9')) { - number_buffer.append(ch); + if (is_double) + fraction_buffer.append(ch); + else + number_buffer.append(ch); ++m_index; continue; } @@ -202,11 +213,31 @@ JsonValue JsonParser::parse_number() } StringView number_string(number_buffer.data(), number_buffer.size()); + StringView fraction_string(fraction_buffer.data(), fraction_buffer.size()); bool ok; - auto value = JsonValue(number_string.to_uint(ok)); - if (!ok) - value = JsonValue(number_string.to_int(ok)); - ASSERT(ok); + JsonValue value; + + if (is_double) { + int whole = number_string.to_uint(ok); + if (!ok) + whole = number_string.to_int(ok); + ASSERT(ok); + + int fraction = fraction_string.to_uint(ok); + ASSERT(ok); + + auto divider = 1; + for (size_t i = 0; i < fraction_buffer.size(); ++i) { + divider *= 10; + } + value = JsonValue((double)whole + ((double)fraction / divider)); + } else { + value = JsonValue(number_string.to_uint(ok)); + if (!ok) + value = JsonValue(number_string.to_int(ok)); + ASSERT(ok); + } + return value; } |