JsonParser: Some minor optimizations

- Return more specific types from parse_array() and parse_object().
- Don't create a throwaway String in extract_while().
- Use a StringView in parse_number() to avoid a throwaway String.
This commit is contained in:
Andreas Kling 2019-08-04 11:47:21 +02:00
parent 93596dc00d
commit b62a12c687
Notes: sideshowbarker 2024-07-19 12:54:10 +09:00
2 changed files with 10 additions and 9 deletions

View file

@ -31,12 +31,12 @@ void JsonParser::consume_while(C condition)
} }
template<typename C> template<typename C>
String JsonParser::extract_while(C condition) Vector<char, 128> JsonParser::extract_while(C condition)
{ {
Vector<char, 1024> buffer; Vector<char, 128> buffer;
while (condition(peek())) while (condition(peek()))
buffer.append(consume()); buffer.append(consume());
return String::copy(buffer); return buffer;
}; };
void JsonParser::consume_whitespace() void JsonParser::consume_whitespace()
@ -95,7 +95,7 @@ String JsonParser::consume_quoted_string()
return String::copy(buffer); return String::copy(buffer);
} }
JsonValue JsonParser::parse_object() JsonObject JsonParser::parse_object()
{ {
JsonObject object; JsonObject object;
consume_specific('{'); consume_specific('{');
@ -119,7 +119,7 @@ JsonValue JsonParser::parse_object()
return object; return object;
} }
JsonValue JsonParser::parse_array() JsonArray JsonParser::parse_array()
{ {
JsonArray array; JsonArray array;
consume_specific('['); consume_specific('[');
@ -145,7 +145,8 @@ JsonValue JsonParser::parse_string()
JsonValue JsonParser::parse_number() JsonValue JsonParser::parse_number()
{ {
auto number_string = extract_while([](char ch) { return ch == '-' || (ch >= '0' && ch <= '9'); }); auto number_buffer = extract_while([](char ch) { return ch == '-' || (ch >= '0' && ch <= '9'); });
StringView number_string(number_buffer.data(), number_buffer.size());
bool ok; bool ok;
auto value = JsonValue(number_string.to_uint(ok)); auto value = JsonValue(number_string.to_uint(ok));
if (!ok) if (!ok)

View file

@ -23,8 +23,8 @@ private:
void consume_specific(char expected_ch); void consume_specific(char expected_ch);
void consume_string(const char*); void consume_string(const char*);
String consume_quoted_string(); String consume_quoted_string();
JsonValue parse_array(); JsonArray parse_array();
JsonValue parse_object(); JsonObject parse_object();
JsonValue parse_number(); JsonValue parse_number();
JsonValue parse_string(); JsonValue parse_string();
JsonValue parse_false(); JsonValue parse_false();
@ -36,7 +36,7 @@ private:
void consume_while(C); void consume_while(C);
template<typename C> template<typename C>
String extract_while(C); Vector<char, 128> extract_while(C);
StringView m_input; StringView m_input;
int m_index { 0 }; int m_index { 0 };