Ver Fonte

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.
Emanuel Sprung há 5 anos atrás
pai
commit
bca5762542
1 ficheiros alterados com 36 adições e 5 exclusões
  1. 36 5
      AK/JsonParser.cpp

+ 36 - 5
AK/JsonParser.cpp

@@ -191,10 +191,21 @@ JsonValue JsonParser::parse_string()
 JsonValue JsonParser::parse_number()
 JsonValue JsonParser::parse_number()
 {
 {
     Vector<char, 128> number_buffer;
     Vector<char, 128> number_buffer;
+    Vector<char, 128> fraction_buffer;
+
+    bool is_double = false;
     for (;;) {
     for (;;) {
         char ch = peek();
         char ch = peek();
+        if (ch == '.') {
+            is_double = true;
+            ++m_index;
+            continue;
+        }
         if (ch == '-' || (ch >= '0' && ch <= '9')) {
         if (ch == '-' || (ch >= '0' && ch <= '9')) {
-            number_buffer.append(ch);
+            if (is_double)
+                fraction_buffer.append(ch);
+            else
+                number_buffer.append(ch);
             ++m_index;
             ++m_index;
             continue;
             continue;
         }
         }
@@ -202,11 +213,31 @@ JsonValue JsonParser::parse_number()
     }
     }
 
 
     StringView number_string(number_buffer.data(), number_buffer.size());
     StringView number_string(number_buffer.data(), number_buffer.size());
+    StringView fraction_string(fraction_buffer.data(), fraction_buffer.size());
     bool ok;
     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;
     return value;
 }
 }