From 9f7fe81ef6982a57681d5f9c7a1e31d36b328e5f Mon Sep 17 00:00:00 2001 From: Riyyi Date: Thu, 23 Jun 2022 13:40:38 +0200 Subject: [PATCH] Util: Add parse() and dump() to Json::Value --- src/util/json/value.cpp | 46 ++++++++++++++++++++++++++++++++++++++++- src/util/json/value.h | 14 +++++++++++-- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/util/json/value.cpp b/src/util/json/value.cpp index f5264ca..f5c7265 100644 --- a/src/util/json/value.cpp +++ b/src/util/json/value.cpp @@ -4,12 +4,15 @@ * SPDX-License-Identifier: MIT */ -#include // assert +#include // assert +#include // uint32_t +#include #include #include // move #include "util/json/array.h" #include "util/json/object.h" +#include "util/json/stringify.h" #include "util/json/value.h" namespace Json { @@ -66,6 +69,24 @@ Value::Value(const Object& value) } Value Value::operator[](size_t index) +// ------------------------------------------ + +Value Value::parse(const std::string& input) +{ + Parser parser(input); + + Value value; + value = parser.parse(); + + return value; +} + +std::string Value::dump(const uint32_t indent, const char indentCharacter) const +{ + Stringify stringify(*this, indent, indentCharacter); + return stringify.dump(); +} + { assert(m_type == Type::Array); return m_value.asArray->values().at(index); @@ -117,4 +138,27 @@ void Value::copyFrom(const Value& other) } } +// ------------------------------------------ + +std::istream& operator>>(std::istream& input, Value& value) +{ + std::string inputString; + + char buffer[4096]; + while (input.read(buffer, sizeof(buffer))) { + inputString.append(buffer, sizeof(buffer)); + } + inputString.append(buffer, input.gcount()); + + Parser parser(inputString); + value = parser.parse(); + + return input; +} + +std::ostream& operator<<(std::ostream& output, const Value& value) +{ + return output << value.dump(4); +} + } // namespace Json diff --git a/src/util/json/value.h b/src/util/json/value.h index 6b68be1..8fa1a45 100644 --- a/src/util/json/value.h +++ b/src/util/json/value.h @@ -7,6 +7,8 @@ #ifndef JSON_VALUE_H #define JSON_VALUE_H +#include // uint32_t +#include // istream, ostream #include namespace Json { @@ -25,7 +27,7 @@ public: Object, // {} }; - Value() {} + Value(std::nullptr_t = nullptr) {} virtual ~Value() { clear(); } // Copy constructor @@ -40,6 +42,11 @@ public: Value(const Array& value); Value(const Object& value); + // ------------------------------------------ + + static Value parse(const std::string& input); + std::string dump(const uint32_t indent = 0, const char indentCharacter = ' ') const; + // Array index operator Value operator[](size_t index); Value operator[](const std::string& key); @@ -64,9 +71,12 @@ private: std::string* asString; Array* asArray; Object* asObject; - } m_value; + } m_value {}; }; +std::istream& operator>>(std::istream& input, Value& value); +std::ostream& operator<<(std::ostream& output, const Value& value); + } // namespace Json #endif // JSON_VALUE_H