From bca57625429fe099df8cbffe24deb11f7536ea1b Mon Sep 17 00:00:00 2001 From: Emanuel Sprung Date: Tue, 24 Mar 2020 21:59:22 +0100 Subject: [PATCH] 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. --- AK/JsonParser.cpp | 41 ++++++++++++++++++++++++++++++++++++----- 1 file 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 number_buffer; + Vector 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; }