/* * Copyright (C) 2022 Riyyi * * SPDX-License-Identifier: MIT */ #ifndef JSON_VALUE_H #define JSON_VALUE_H #include // nullptr_t, size_t #include // uint32_t #include #include // istream, ostream #include #include // forward #include "util/json/fromjson.h" #include "util/json/tojson.h" namespace Json { class Array; class Object; class Value { private: friend Detail::jsonConstructor; friend class Parser; friend class Serializer; public: enum class Type { Null, // null (case sensitive!) Bool, // true/false (case sensitive!) Number, // 123 String, // "" Array, // [] Object, // {} }; // Constructors Value(std::nullptr_t = nullptr); Value(Type type); Value(const std::initializer_list& values); template Value(T value) { toJson(*this, std::forward(value)); } // Destructor virtual ~Value() { clear(); } // Copy constructor Value(const Value& other); // Assignment operator Value& operator=(const Value& other); // -------------------------------------- static Value parse(const std::string& input); std::string dump(const uint32_t indent = 0, const char indentCharacter = ' ') const; void emplace_back(Value value); void emplace(const std::string& key, Value value); bool exists(size_t index) const; bool exists(const std::string& key) const; // -------------------------------------- // Array index operator Value& operator[](size_t index); Value& operator[](const std::string& key); const Value& operator[](size_t index) const; const Value& operator[](const std::string& key) const; Value& at(size_t index); Value& at(const std::string& key); const Value& at(size_t index) const; const Value& at(const std::string& key) const; // -------------------------------------- template T get() const { T type; fromJson(*this, type); return type; } template void getTo(T& type) const { fromJson(*this, type); } // -------------------------------------- Type type() const { return m_type; } size_t size() const; bool asBool() const { return m_value.boolean; } double asDouble() const { return m_value.number; } const std::string& asString() const { return *m_value.string; } const Array& asArray() const { return *m_value.array; } const Object& asObject() const { return *m_value.object; } private: void create(); void clear(); void copyFrom(const Value& other); Type m_type { Type::Null }; union { bool boolean; double number; std::string* string; Array* array; Object* object; } m_value {}; }; std::istream& operator>>(std::istream& input, Value& value); std::ostream& operator<<(std::ostream& output, const Value& value); } // namespace Json /** * User-defined string literal * * Example usage: auto json = "[ 3.14, true, null ]"_json; */ inline Json::Value operator"" _json(const char* input, size_t length) { return Json::Value::parse(std::string(input, length)); } #endif // JSON_VALUE_H