Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -----------------------------------------------------------------------
- json.h
- -----------------------------------------------------------------------
- #pragma once
- #include <iostream>
- #include <map>
- #include <string>
- #include <vector>
- #include <variant>
- namespace json {
- class Node;
- using Dict = std::map<std::string, Node>;
- using Array = std::vector<Node>;
- class ParsingError : public std::runtime_error {
- public:
- using runtime_error::runtime_error;
- };
- class Node {
- public:
- using Value = std::variant<std::nullptr_t,
- Array,
- Dict,
- bool,
- int,
- double,
- std::string>;
- Node() = default;
- Node(bool value);
- Node(Array array);
- Node(Dict map);
- Node(int value);
- Node(std::string value);
- Node(std::nullptr_t);
- Node(double value);
- const Array& AsArray() const;
- const Dict& AsMap() const;
- int AsInt() const;
- double AsDouble() const;
- bool AsBool() const;
- const std::string& AsString() const;
- bool IsNull() const;
- bool IsInt() const;
- bool IsDouble() const;
- bool IsPureDouble() const;
- bool IsBool() const;
- bool IsString() const;
- bool IsArray() const;
- bool IsMap() const;
- const Value& GetValue() const { return value_; };
- private:
- Value value_;
- };
- inline bool operator==(const Node& lhs, const Node& rhs) {
- return lhs.GetValue() == rhs.GetValue();
- }
- inline bool operator!=(const Node& lhs, const Node& rhs) {
- return !(lhs == rhs);
- }
- class Document {
- public:
- Document() = default;
- explicit Document(Node root);
- const Node& GetRoot() const;
- private:
- Node root_;
- };
- Document Load(std::istream& input);
- inline bool operator==(const Document& lhs, const Document& rhs) {
- return lhs.GetRoot() == rhs.GetRoot();
- }
- inline bool operator!=(const Document& lhs, const Document& rhs) {
- return !(lhs == rhs);
- }
- void Print(const Document& doc, std::ostream& output);
- }//end namespace json
- -----------------------------------------------------------------------
- json.cpp
- -----------------------------------------------------------------------
- #include "json.h"
- using namespace std;
- namespace json {
- namespace {
- Node LoadNode(istream& input);
- std::string LoadLiteral(std::istream& input) {
- std::string str;
- while (std::isalpha(input.peek())) {
- str.push_back(static_cast<char>(input.get()));
- }
- return str;
- }
- Node LoadArray(std::istream& input) {
- std::vector<Node> array;
- for (char ch; input >> ch && ch != ']';) {
- if (ch != ',') {
- input.putback(ch);
- }
- array.push_back(LoadNode(input));
- }
- if (!input) {
- throw ParsingError("unable to parse array"s);
- }
- return Node(array);
- }
- Node LoadNull(std::istream& input) {
- if (auto literal = LoadLiteral(input); literal == "null"sv) {
- return Node(nullptr);
- } else {
- throw ParsingError("unable to parse '"s + literal + "' as null"s);
- }
- }
- Node LoadBool(std::istream& input) {
- const auto str = LoadLiteral(input);
- if (str == "true"sv) {
- return Node(true);
- } else if (str == "false"sv) {
- return Node(false);
- } else {
- throw ParsingError("unable to parse '"s + str + "' as bool"s);
- }
- }
- Node LoadNumber(std::istream& input) {
- std::string number;
- auto read_char = [&number, &input] {
- number += static_cast<char>(input.get());
- if (!input) {
- throw ParsingError("unable to read number"s);
- }
- };
- auto read_digits = [&input, read_char] {
- if (!std::isdigit(input.peek())) {
- throw ParsingError("A digit is expected"s);
- } else {
- while (std::isdigit(input.peek())) {
- read_char();
- }
- }
- };
- if (input.peek() == '-') {
- read_char();
- }
- if (input.peek() == '0') {
- read_char();
- } else {
- read_digits();
- }
- bool is_int = true;
- if (input.peek() == '.') {
- read_char();
- read_digits();
- is_int = false;
- }
- if (int ch = input.peek(); ch == 'e' || ch == 'E') {
- read_char();
- if (ch = input.peek(); ch == '+' || ch == '-') {
- read_char();
- }
- read_digits();
- is_int = false;
- }
- try {
- if (is_int) {
- try {
- return Node(std::stoi(number));
- } catch (...) {}
- }
- return Node(std::stod(number));
- } catch (...) {
- throw ParsingError("unable to convert "s + number + " to number"s);
- }
- }
- Node LoadString(std::istream& input) {
- auto it = std::istreambuf_iterator<char>(input);
- auto end = std::istreambuf_iterator<char>();
- std::string str;
- while (true) {
- if (it == end) {
- throw ParsingError("unable to parse string");
- }
- const char ch = *it;
- if (ch == '"') {
- ++it;
- break;
- } else if (ch == '\\') {
- ++it;
- if (it == end) {
- throw ParsingError("unable to parse string");
- }
- const char esc_ch = *(it);
- switch (esc_ch) {
- case 'n':
- str.push_back('\n');
- break;
- case 't':
- str.push_back('\t');
- break;
- case 'r':
- str.push_back('\r');
- break;
- case '"':
- str.push_back('"');
- break;
- case '\\':
- str.push_back('\\');
- break;
- default:
- throw ParsingError("invalid esc \\"s + esc_ch);
- }
- } else if (ch == '\n' || ch == '\r') {
- throw ParsingError("invalid line end"s);
- } else {
- str.push_back(ch);
- }
- ++it;
- }
- return Node(str);
- }
- Node LoadDict(std::istream& input) {
- Dict dictionary;
- for (char ch; input >> ch && ch != '}';) {
- if (ch == '"') {
- std::string key = LoadString(input).AsString();
- if (input >> ch && ch == ':') {
- if (dictionary.find(key) != dictionary.end()) {
- throw ParsingError("duplicate key '"s + key + "'found");
- }
- dictionary.emplace(std::move(key), LoadNode(input));
- } else {
- throw ParsingError(": expected. but '"s + ch + "' found"s);
- }
- } else if (ch != ',') {
- throw ParsingError("',' expected. but '"s + ch + "' found"s);
- }
- }
- if (!input) {
- throw ParsingError("unable to parse dictionary"s);
- } else {
- return Node(dictionary);
- }
- }
- Node LoadNode(std::istream& input) {
- char ch;
- if (!(input >> ch)) {
- throw ParsingError(""s);
- } else {
- switch (ch) {
- case '[':
- return LoadArray(input);
- case '{':
- return LoadDict(input);
- case '"':
- return LoadString(input);
- case 't': case 'f':
- input.putback(ch);
- return LoadBool(input);
- case 'n':
- input.putback(ch);
- return LoadNull(input);
- default:
- input.putback(ch);
- return LoadNumber(input);
- }
- }
- }
- }//end namespace
- Node::Node(Array array) : value_(std::move(array)) {}
- Node::Node(std::nullptr_t) : Node() {}
- Node::Node(bool value) : value_(value) {}
- Node::Node(Dict map) : value_(std::move(map)) {}
- Node::Node(int value) : value_(value) {}
- Node::Node(string value) : value_(std::move(value)) {}
- Node::Node(double value) : value_(value) {}
- const Array& Node::AsArray() const {
- using namespace std::literals;
- if (!IsArray()) {
- throw std::logic_error("value is not an array"s);
- } else {
- return std::get<Array>(value_);
- }
- }
- const Dict& Node::AsMap() const {
- using namespace std::literals;
- if (!IsMap()) {
- throw std::logic_error("value is not a dictionary"s);
- } else {
- return std::get<Dict>(value_);
- }
- }
- const string& Node::AsString() const {
- using namespace std::literals;
- if (!IsString()) {
- throw std::logic_error("value is not a string"s);
- } else {
- return std::get<std::string>(value_);
- }
- }
- int Node::AsInt() const {
- using namespace std::literals;
- if (!IsInt()) {
- throw std::logic_error("value is not an int"s);
- } else {
- return std::get<int>(value_);
- }
- }
- double Node::AsDouble() const {
- using namespace std::literals;
- if (!IsDouble()) {
- throw std::logic_error("value is not a double"s);
- } else if (IsPureDouble()) {
- return std::get<double>(value_);
- } else {
- return AsInt();
- }
- }
- bool Node::AsBool() const {
- using namespace std::literals;
- if (!IsBool()) {
- throw std::logic_error("value is not a bool"s);
- } else {
- return std::get<bool>(value_);
- }
- }
- bool Node::IsNull() const {return std::holds_alternative<std::nullptr_t>(value_);}
- bool Node::IsInt() const {return std::holds_alternative<int>(value_);}
- bool Node::IsDouble() const {return IsPureDouble() || IsInt();}
- bool Node::IsPureDouble() const {return std::holds_alternative<double>(value_);}
- bool Node::IsBool() const {return std::holds_alternative<bool>(value_);}
- bool Node::IsString() const {return std::holds_alternative<std::string>(value_);}
- bool Node::IsArray() const {return std::holds_alternative<Array>(value_);}
- bool Node::IsMap() const {return std::holds_alternative<Dict>(value_);}
- Document::Document(Node root) : root_(std::move(root)) {}
- const Node& Document::GetRoot() const {return root_;}
- Document Load(istream& input) {return Document{LoadNode(input)};}
- struct PrintContext {
- std::ostream& out;
- int indent_step = 4;
- int indent = 0;
- void PrintIndent() const {
- for (int i = 0; i < indent; ++i) {
- out.put(' ');
- }
- }
- [[nodiscard]] PrintContext Indented() const {
- return {out,
- indent_step,
- indent + indent_step};
- }
- };
- void PrintNode(const Node& node, const PrintContext& context);
- void PrintString(const std::string& value, std::ostream& out) {
- out.put('"');
- for (const char ch : value) {
- switch (ch) {
- case '\r':
- out << R"(\r)";
- break;
- case '\n':
- out << R"(\n)";
- break;
- case '"':
- out << R"(\")";
- break;
- case '\\':
- out << R"(\\)";
- break;
- default:
- out.put(ch);
- break;
- }
- }
- out.put('"');
- }
- template <typename Value>
- void PrintValue(const Value& value, const PrintContext& context) {
- context.out << value;
- }
- template <>
- void PrintValue<std::string>(const std::string& value, const PrintContext& context) {
- PrintString(value, context.out);
- }
- void PrintValue(const std::nullptr_t&, const PrintContext& context) {
- context.out << "null"s;
- }
- void PrintValue(bool value, const PrintContext& context) {
- context.out << std::boolalpha << value;
- }
- [[maybe_unused]] void PrintValue(Array nodes, const PrintContext& context) {
- std::ostream& out = context.out;
- out << "[\n"sv;
- bool first = true;
- auto inner_context = context.Indented();
- for (const Node& node : nodes) {
- if (first) {
- first = false;
- } else {
- out << ",\n"sv;
- }
- inner_context.PrintIndent();
- PrintNode(node, inner_context);
- }
- out.put('\n');
- context.PrintIndent();
- out.put(']');
- }
- [[maybe_unused]] void PrintValue(Dict nodes, const PrintContext& context) {
- std::ostream& out = context.out;
- out << "{\n"sv;
- bool first = true;
- auto inner_context = context.Indented();
- for (const auto& [key, node] : nodes) {
- if (first) {
- first = false;
- } else {
- out << ",\n"sv;
- }
- inner_context.PrintIndent();
- PrintString(key, context.out);
- out << ": "sv;
- PrintNode(node, inner_context);
- }
- out.put('\n');
- context.PrintIndent();
- out.put('}');
- }
- void PrintNode(const Node& node, const PrintContext& context) {
- std::visit([&context](const auto& value) {
- PrintValue(value, context);
- },node.GetValue());
- }
- void Print(const Document& document, std::ostream& output) {
- PrintNode(document.GetRoot(), PrintContext{output});
- }
- }//end namespace json
- -----------------------------------------------------------------------
- main.cpp
- -----------------------------------------------------------------------
- #include <cassert>
- #include <chrono>
- #include <sstream>
- #include <string_view>
- #include "json.h"
- using namespace json;
- using namespace std::literals;
- namespace {
- json::Document LoadJSON(const std::string& s) {
- std::istringstream strm(s);
- return json::Load(strm);
- }
- std::string Print(const Node& node) {
- std::ostringstream out;
- Print(Document{node}, out);
- return out.str();
- }
- void MustFailToLoad(const std::string& s) {
- try {
- LoadJSON(s);
- std::cerr << "ParsingError exception is expected on '"sv << s << "'"sv << std::endl;
- assert(false);
- } catch (const json::ParsingError&) {
- // ok
- } catch (const std::exception& e) {
- std::cerr << "exception thrown: "sv << e.what() << std::endl;
- assert(false);
- } catch (...) {
- std::cerr << "Unexpected error"sv << std::endl;
- assert(false);
- }
- }
- template <typename Fn>
- void MustThrowLogicError(Fn fn) {
- try {
- fn();
- std::cerr << "logic_error is expected"sv << std::endl;
- assert(false);
- } catch (const std::logic_error&) {
- // ok
- } catch (const std::exception& e) {
- std::cerr << "exception thrown: "sv << e.what() << std::endl;
- assert(false);
- } catch (...) {
- std::cerr << "Unexpected error"sv << std::endl;
- assert(false);
- }
- }
- void TestNull() {
- Node null_node;
- assert(null_node.IsNull());
- assert(!null_node.IsInt());
- assert(!null_node.IsDouble());
- assert(!null_node.IsPureDouble());
- assert(!null_node.IsString());
- assert(!null_node.IsArray());
- assert(!null_node.IsMap());
- Node null_node1{nullptr};
- assert(null_node1.IsNull());
- assert(Print(null_node) == "null"s);
- assert(null_node == null_node1);
- assert(!(null_node != null_node1));
- const Node node = LoadJSON("null"s).GetRoot();
- assert(node.IsNull());
- assert(node == null_node);
- assert(LoadJSON(" \t\r\n\n\r null \t\r\n\n\r "s).GetRoot() == null_node);
- }
- void TestNumbers() {
- const Node int_node{42};
- assert(int_node.IsInt());
- assert(int_node.AsInt() == 42);
- assert(int_node.IsDouble());
- assert(int_node.AsDouble() == 42.0);
- assert(!int_node.IsPureDouble());
- assert(int_node == Node{42});
- assert(int_node != Node{42.0});
- const Node dbl_node{123.45};
- assert(dbl_node.IsDouble());
- assert(dbl_node.AsDouble() == 123.45);
- assert(dbl_node.IsPureDouble());
- assert(!dbl_node.IsInt());
- assert(Print(int_node) == "42"s);
- assert(Print(dbl_node) == "123.45"s);
- assert(Print(Node{-42}) == "-42"s);
- assert(Print(Node{-3.5}) == "-3.5"s);
- assert(LoadJSON("42"s).GetRoot() == int_node);
- assert(LoadJSON("123.45"s).GetRoot() == dbl_node);
- assert(LoadJSON("0.25"s).GetRoot().AsDouble() == 0.25);
- assert(LoadJSON("3e5"s).GetRoot().AsDouble() == 3e5);
- assert(LoadJSON("1.2e-5"s).GetRoot().AsDouble() == 1.2e-5);
- assert(LoadJSON("1.2e+5"s).GetRoot().AsDouble() == 1.2e5);
- assert(LoadJSON("-123456"s).GetRoot().AsInt() == -123456);
- assert(LoadJSON("0").GetRoot() == Node{0});
- assert(LoadJSON("0.0").GetRoot() == Node{0.0});
- assert(LoadJSON(" \t\r\n\n\r 0.0 \t\r\n\n\r ").GetRoot() == Node{0.0});
- }
- void TestStrings() {
- Node str_node{"Hello, \"everybody\""s};
- assert(str_node.IsString());
- assert(str_node.AsString() == "Hello, \"everybody\""s);
- assert(!str_node.IsInt());
- assert(!str_node.IsDouble());
- assert(Print(str_node) == "\"Hello, \\\"everybody\\\"\""s);
- assert(LoadJSON(Print(str_node)).GetRoot() == str_node);
- const std::string escape_chars
- = R"("\r\n\t\"\\")"s;
- assert(Print(LoadJSON(escape_chars).GetRoot()) == "\"\\r\\n\t\\\"\\\\\""s);
- assert(LoadJSON("\t\r\n\n\r \"Hello\" \t\r\n\n\r ").GetRoot() == Node{"Hello"s});
- }
- void TestBool() {
- Node true_node{true};
- assert(true_node.IsBool());
- assert(true_node.AsBool());
- Node false_node{false};
- assert(false_node.IsBool());
- assert(!false_node.AsBool());
- assert(Print(true_node) == "true"s);
- assert(Print(false_node) == "false"s);
- assert(LoadJSON("true"s).GetRoot() == true_node);
- assert(LoadJSON("false"s).GetRoot() == false_node);
- assert(LoadJSON(" \t\r\n\n\r true \r\n"s).GetRoot() == true_node);
- assert(LoadJSON(" \t\r\n\n\r false \t\r\n\n\r "s).GetRoot() == false_node);
- }
- void TestArray() {
- Node arr_node{Array{1, 1.23, "Hello"s}};
- assert(arr_node.IsArray());
- const Array& arr = arr_node.AsArray();
- assert(arr.size() == 3);
- assert(arr.at(0).AsInt() == 1);
- assert(LoadJSON("[1,1.23,\"Hello\"]"s).GetRoot() == arr_node);
- assert(LoadJSON(Print(arr_node)).GetRoot() == arr_node);
- assert(LoadJSON(R"( [ 1 , 1.23, "Hello" ] )"s).GetRoot() == arr_node);
- assert(LoadJSON("[ 1 \r \n , \r\n\t 1.23, \n \n \t\t \"Hello\" \t \n ] \n "s).GetRoot()
- == arr_node);
- }
- void TestMap() {
- Node dict_node{Dict{{"key1"s, "value1"s}, {"key2"s, 42}}};
- assert(dict_node.IsMap());
- const Dict& dict = dict_node.AsMap();
- assert(dict.size() == 2);
- assert(dict.at("key1"s).AsString() == "value1"s);
- assert(dict.at("key2"s).AsInt() == 42);
- assert(LoadJSON("{ \"key1\": \"value1\", \"key2\": 42 }"s).GetRoot() == dict_node);
- assert(LoadJSON(Print(dict_node)).GetRoot() == dict_node);
- assert(
- LoadJSON(
- "\t\r\n\n\r { \t\r\n\n\r \"key1\" \t\r\n\n\r: \t\r\n\n\r \"value1\" \t\r\n\n\r , \t\r\n\n\r \"key2\" \t\r\n\n\r : \t\r\n\n\r 42 \t\r\n\n\r } \t\r\n\n\r"s)
- .GetRoot()
- == dict_node);
- }
- void TestErrorHandling() {
- MustFailToLoad("["s);
- MustFailToLoad("]"s);
- MustFailToLoad("{"s);
- MustFailToLoad("}"s);
- MustFailToLoad("\"hello"s); // незакрытая кавычка
- MustFailToLoad("tru"s);
- MustFailToLoad("fals"s);
- MustFailToLoad("nul"s);
- Node dbl_node{3.5};
- MustThrowLogicError([&dbl_node] {
- dbl_node.AsInt();
- });
- MustThrowLogicError([&dbl_node] {
- dbl_node.AsString();
- });
- MustThrowLogicError([&dbl_node] {
- dbl_node.AsArray();
- });
- Node array_node{Array{}};
- MustThrowLogicError([&array_node] {
- array_node.AsMap();
- });
- MustThrowLogicError([&array_node] {
- array_node.AsDouble();
- });
- MustThrowLogicError([&array_node] {
- array_node.AsBool();
- });
- }
- void Benchmark() {
- const auto start = std::chrono::steady_clock::now();
- Array arr;
- arr.reserve(1'000);
- for (int i = 0; i < 1'000; ++i) {
- arr.emplace_back(Dict{
- {"int"s, 42},
- {"double"s, 42.1},
- {"null"s, nullptr},
- {"string"s, "hello"s},
- {"array"s, Array{1, 2, 3}},
- {"bool"s, true},
- {"map"s, Dict{{"key"s, "value"s}}},
- });
- }
- std::stringstream strm;
- json::Print(Document{arr}, strm);
- const auto doc = json::Load(strm);
- assert(doc.GetRoot() == arr);
- const auto duration = std::chrono::steady_clock::now() - start;
- std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms"sv
- << std::endl;
- }
- }//end namespace
- int main() {
- TestNull();
- TestNumbers();
- TestStrings();
- TestBool();
- TestArray();
- TestMap();
- TestErrorHandling();
- Benchmark();
- }
Add Comment
Please, Sign In to add comment