shushus

Спринт 11. Runtime-полиморфизм с std::variant. Задание 2.

Apr 6th, 2023
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 20.97 KB | None | 0 0
  1. -----------------------------------------------------------------------
  2. json.h
  3. -----------------------------------------------------------------------
  4. #pragma once
  5.  
  6. #include <iostream>
  7. #include <map>
  8. #include <string>
  9. #include <vector>
  10. #include <variant>
  11.  
  12. namespace json {
  13.  
  14. class Node;
  15.  
  16. using Dict = std::map<std::string, Node>;
  17. using Array = std::vector<Node>;
  18.  
  19. class ParsingError : public std::runtime_error {
  20. public:
  21.     using runtime_error::runtime_error;
  22. };
  23.  
  24. class Node {
  25. public:
  26.  
  27.     using Value =  std::variant<std::nullptr_t,
  28.                                 Array,
  29.                                 Dict,
  30.                                 bool,
  31.                                 int,
  32.                                 double,
  33.                                 std::string>;
  34.  
  35.     Node() = default;
  36.     Node(bool value);
  37.     Node(Array array);
  38.     Node(Dict map);
  39.     Node(int value);
  40.     Node(std::string value);
  41.     Node(std::nullptr_t);
  42.     Node(double value);
  43.    
  44.     const Array& AsArray() const;
  45.     const Dict& AsMap() const;
  46.     int AsInt() const;
  47.     double AsDouble() const;
  48.     bool AsBool() const;
  49.     const std::string& AsString() const;
  50.  
  51.     bool IsNull() const;
  52.     bool IsInt() const;
  53.     bool IsDouble() const;
  54.     bool IsPureDouble() const;
  55.     bool IsBool() const;
  56.     bool IsString() const;
  57.     bool IsArray() const;
  58.     bool IsMap() const;
  59.  
  60.     const Value& GetValue() const { return value_; };
  61.        
  62. private:
  63.     Value value_;
  64. };
  65.  
  66. inline bool operator==(const Node& lhs, const Node& rhs) {
  67.     return lhs.GetValue() == rhs.GetValue();
  68. }  
  69. inline bool operator!=(const Node& lhs, const Node& rhs) {
  70.     return !(lhs == rhs);
  71. }
  72.    
  73. class Document {
  74. public:
  75.     Document() = default;
  76.     explicit Document(Node root);
  77.     const Node& GetRoot() const;
  78.  
  79. private:
  80.     Node root_;
  81. };
  82.  
  83. Document Load(std::istream& input);
  84.  
  85. inline bool operator==(const Document& lhs, const Document& rhs) {
  86.     return lhs.GetRoot() == rhs.GetRoot();
  87. }
  88. inline bool operator!=(const Document& lhs, const Document& rhs) {
  89.     return !(lhs == rhs);
  90. }
  91.    
  92. void Print(const Document& doc, std::ostream& output);
  93.  
  94. }//end namespace json
  95. -----------------------------------------------------------------------
  96. json.cpp
  97. -----------------------------------------------------------------------
  98. #include "json.h"
  99.  
  100. using namespace std;
  101. namespace json {
  102. namespace {
  103.  
  104. Node LoadNode(istream& input);
  105.  
  106. std::string LoadLiteral(std::istream& input) {
  107.     std::string str;
  108.    
  109.     while (std::isalpha(input.peek())) {
  110.         str.push_back(static_cast<char>(input.get()));
  111.     }
  112.     return str;
  113. }
  114.  
  115. Node LoadArray(std::istream& input) {
  116.     std::vector<Node> array;
  117.    
  118.     for (char ch; input >> ch && ch != ']';) {
  119.         if (ch != ',') {
  120.             input.putback(ch);
  121.         }
  122.        
  123.         array.push_back(LoadNode(input));
  124.     }
  125.  
  126.     if (!input) {
  127.         throw ParsingError("unable to parse array"s);
  128.     }
  129.  
  130.     return Node(array);
  131. }
  132.  
  133. Node LoadNull(std::istream& input) {
  134.     if (auto literal = LoadLiteral(input); literal == "null"sv) {
  135.         return Node(nullptr);
  136.     } else {
  137.         throw ParsingError("unable to parse '"s + literal + "' as null"s);
  138.     }
  139. }
  140.  
  141. Node LoadBool(std::istream& input) {
  142.     const auto str = LoadLiteral(input);
  143.  
  144.     if (str == "true"sv) {
  145.         return Node(true);
  146.     } else if (str == "false"sv) {
  147.         return Node(false);
  148.     } else {
  149.         throw ParsingError("unable to parse '"s + str + "' as bool"s);
  150.     }
  151. }
  152.  
  153. Node LoadNumber(std::istream& input) {
  154.     std::string number;
  155.  
  156.     auto read_char = [&number, &input] {
  157.         number += static_cast<char>(input.get());
  158.        
  159.         if (!input) {
  160.             throw ParsingError("unable to read number"s);
  161.         }
  162.     };
  163.  
  164.     auto read_digits = [&input, read_char] {
  165.        
  166.         if (!std::isdigit(input.peek())) {
  167.             throw ParsingError("A digit is expected"s);
  168.         } else {
  169.             while (std::isdigit(input.peek())) {
  170.                 read_char();
  171.             }  
  172.         }
  173.     };
  174.  
  175.     if (input.peek() == '-') {
  176.         read_char();
  177.     }
  178.  
  179.     if (input.peek() == '0') {
  180.         read_char();
  181.     } else {
  182.         read_digits();
  183.     }
  184.  
  185.     bool is_int = true;
  186.     if (input.peek() == '.') {
  187.         read_char();
  188.         read_digits();
  189.         is_int = false;
  190.     }
  191.  
  192.     if (int ch = input.peek(); ch == 'e' || ch == 'E') {
  193.         read_char();
  194.        
  195.         if (ch = input.peek(); ch == '+' || ch == '-') {
  196.             read_char();
  197.         }
  198.  
  199.         read_digits();
  200.         is_int = false;
  201.     }
  202.  
  203.     try {
  204.         if (is_int) {
  205.             try {
  206.                 return Node(std::stoi(number));
  207.                
  208.             } catch (...) {}
  209.         }
  210.         return Node(std::stod(number));
  211.        
  212.     } catch (...) {
  213.         throw ParsingError("unable to convert "s + number + " to number"s);
  214.     }
  215. }
  216.  
  217. Node LoadString(std::istream& input) {
  218.     auto it = std::istreambuf_iterator<char>(input);
  219.     auto end = std::istreambuf_iterator<char>();
  220.     std::string str;
  221.    
  222.     while (true) {
  223.         if (it == end) {
  224.             throw ParsingError("unable to parse string");
  225.         }
  226.        
  227.         const char ch = *it;
  228.         if (ch == '"') {
  229.             ++it;
  230.             break;
  231.            
  232.         } else if (ch == '\\') {
  233.             ++it;
  234.             if (it == end) {
  235.                 throw ParsingError("unable to parse string");
  236.             }
  237.            
  238.             const char esc_ch = *(it);
  239.             switch (esc_ch) {
  240.                 case 'n':
  241.                     str.push_back('\n');
  242.                     break;
  243.                 case 't':
  244.                     str.push_back('\t');
  245.                     break;
  246.                 case 'r':
  247.                     str.push_back('\r');
  248.                     break;
  249.                 case '"':
  250.                     str.push_back('"');
  251.                     break;
  252.                 case '\\':
  253.                     str.push_back('\\');
  254.                     break;
  255.                 default:
  256.                     throw ParsingError("invalid esc \\"s + esc_ch);
  257.             }
  258.            
  259.         } else if (ch == '\n' || ch == '\r') {
  260.             throw ParsingError("invalid line end"s);
  261.         } else {
  262.             str.push_back(ch);
  263.         }
  264.        
  265.         ++it;
  266.     }
  267.    
  268.     return Node(str);
  269. }
  270.  
  271. Node LoadDict(std::istream& input) {
  272.     Dict dictionary;
  273.  
  274.     for (char ch; input >> ch && ch != '}';) {
  275.        
  276.         if (ch == '"') {
  277.             std::string key = LoadString(input).AsString();
  278.  
  279.             if (input >> ch && ch == ':') {
  280.                
  281.                 if (dictionary.find(key) != dictionary.end()) {
  282.                     throw ParsingError("duplicate key '"s + key + "'found");
  283.                 }
  284.  
  285.                 dictionary.emplace(std::move(key), LoadNode(input));
  286.                
  287.             } else {
  288.                 throw ParsingError(": expected. but '"s + ch + "' found"s);
  289.             }
  290.            
  291.         } else if (ch != ',') {
  292.             throw ParsingError("',' expected. but '"s + ch + "' found"s);
  293.         }
  294.     }
  295.  
  296.     if (!input) {
  297.         throw ParsingError("unable to parse dictionary"s);
  298.     } else {
  299.         return Node(dictionary);
  300.     }
  301.    
  302. }
  303.  
  304. Node LoadNode(std::istream& input) {
  305.     char ch;
  306.    
  307.     if (!(input >> ch)) {
  308.         throw ParsingError(""s);
  309.     } else {
  310.         switch (ch) {
  311.         case '[':
  312.             return LoadArray(input);
  313.         case '{':
  314.             return LoadDict(input);
  315.         case '"':
  316.             return LoadString(input);
  317.         case 't': case 'f':
  318.             input.putback(ch);
  319.             return LoadBool(input);
  320.         case 'n':
  321.             input.putback(ch);
  322.             return LoadNull(input);
  323.         default:
  324.             input.putback(ch);
  325.             return LoadNumber(input);
  326.         }
  327.     }
  328. }
  329.  
  330. }//end namespace
  331.    
  332. Node::Node(Array array) : value_(std::move(array)) {}    
  333. Node::Node(std::nullptr_t) : Node() {}
  334. Node::Node(bool value) : value_(value) {}
  335. Node::Node(Dict map) : value_(std::move(map)) {}
  336. Node::Node(int value) : value_(value) {}
  337. Node::Node(string value) : value_(std::move(value)) {}
  338. Node::Node(double value) : value_(value) {}
  339.    
  340. const Array& Node::AsArray() const {
  341.     using namespace std::literals;
  342.    
  343.     if (!IsArray()) {
  344.         throw std::logic_error("value is not an array"s);
  345.     } else {
  346.         return std::get<Array>(value_);
  347.     }
  348. }
  349.  
  350. const Dict& Node::AsMap() const {
  351.     using namespace std::literals;
  352.    
  353.     if (!IsMap()) {
  354.         throw std::logic_error("value is not a dictionary"s);
  355.     } else {
  356.         return std::get<Dict>(value_);  
  357.     }
  358. }
  359.  
  360. const string& Node::AsString() const {
  361.     using namespace std::literals;
  362.    
  363.     if (!IsString()) {
  364.         throw std::logic_error("value is not a string"s);
  365.     } else {
  366.         return std::get<std::string>(value_);        
  367.     }
  368. }
  369.    
  370. int Node::AsInt() const {
  371.     using namespace std::literals;
  372.    
  373.     if (!IsInt()) {
  374.         throw std::logic_error("value is not an int"s);
  375.     } else {
  376.         return std::get<int>(value_);    
  377.     }
  378. }
  379.  
  380. double Node::AsDouble() const {
  381.     using namespace std::literals;
  382.    
  383.     if (!IsDouble()) {
  384.         throw std::logic_error("value is not a double"s);
  385.     } else if (IsPureDouble()) {
  386.         return std::get<double>(value_);
  387.     } else {
  388.         return AsInt();
  389.     }    
  390. }
  391.  
  392. bool Node::AsBool() const {
  393.     using namespace std::literals;
  394.    
  395.     if (!IsBool()) {
  396.         throw std::logic_error("value is not a bool"s);
  397.     } else {
  398.         return std::get<bool>(value_);  
  399.     }
  400. }
  401.    
  402. bool Node::IsNull() const {return std::holds_alternative<std::nullptr_t>(value_);}    
  403. bool Node::IsInt() const {return std::holds_alternative<int>(value_);}
  404. bool Node::IsDouble() const {return IsPureDouble() || IsInt();}  
  405. bool Node::IsPureDouble() const {return std::holds_alternative<double>(value_);}    
  406. bool Node::IsBool() const {return std::holds_alternative<bool>(value_);}    
  407. bool Node::IsString() const {return std::holds_alternative<std::string>(value_);}    
  408. bool Node::IsArray() const {return std::holds_alternative<Array>(value_);}  
  409. bool Node::IsMap() const {return std::holds_alternative<Dict>(value_);}
  410.        
  411. Document::Document(Node root) : root_(std::move(root)) {}
  412. const Node& Document::GetRoot() const {return root_;}
  413. Document Load(istream& input) {return Document{LoadNode(input)};}
  414.  
  415. struct PrintContext {
  416.     std::ostream& out;
  417.     int indent_step = 4;
  418.     int indent = 0;
  419.  
  420.     void PrintIndent() const {
  421.         for (int i = 0; i < indent; ++i) {
  422.             out.put(' ');
  423.         }
  424.     }
  425.  
  426.     [[nodiscard]] PrintContext Indented() const {
  427.         return {out,
  428.                 indent_step,
  429.                 indent + indent_step};
  430.     }
  431. };
  432.  
  433. void PrintNode(const Node& node, const PrintContext& context);
  434.    
  435.  
  436. void PrintString(const std::string& value, std::ostream& out) {
  437.     out.put('"');
  438.    
  439.     for (const char ch : value) {
  440.         switch (ch) {
  441.             case '\r':
  442.                 out << R"(\r)";
  443.                 break;
  444.             case '\n':
  445.                 out << R"(\n)";
  446.                 break;
  447.             case '"':
  448.                 out << R"(\")";
  449.                 break;
  450.             case '\\':
  451.                 out << R"(\\)";
  452.                 break;
  453.             default:
  454.                 out.put(ch);
  455.                 break;
  456.         }
  457.     }
  458.    
  459.     out.put('"');
  460. }
  461.  
  462. template <typename Value>
  463. void PrintValue(const Value& value, const PrintContext& context) {
  464.     context.out << value;
  465. }
  466.  
  467. template <>
  468. void PrintValue<std::string>(const std::string& value, const PrintContext& context) {
  469.     PrintString(value, context.out);
  470. }
  471.  
  472. void PrintValue(const std::nullptr_t&, const PrintContext& context) {
  473.     context.out << "null"s;
  474. }
  475.  
  476. void PrintValue(bool value, const PrintContext& context) {
  477.     context.out << std::boolalpha << value;
  478. }
  479.  
  480. [[maybe_unused]] void PrintValue(Array nodes, const PrintContext& context) {
  481.     std::ostream& out = context.out;
  482.     out << "[\n"sv;
  483.     bool first = true;
  484.     auto inner_context = context.Indented();
  485.    
  486.     for (const Node& node : nodes) {
  487.         if (first) {
  488.             first = false;
  489.         } else {
  490.             out << ",\n"sv;
  491.         }
  492.  
  493.         inner_context.PrintIndent();
  494.         PrintNode(node, inner_context);
  495.     }
  496.  
  497.     out.put('\n');
  498.     context.PrintIndent();
  499.     out.put(']');
  500. }
  501.  
  502. [[maybe_unused]] void PrintValue(Dict nodes, const PrintContext& context) {
  503.     std::ostream& out = context.out;
  504.     out << "{\n"sv;
  505.     bool first = true;
  506.     auto inner_context = context.Indented();
  507.    
  508.     for (const auto& [key, node] : nodes) {
  509.         if (first) {
  510.             first = false;
  511.         } else {
  512.             out << ",\n"sv;
  513.         }
  514.  
  515.         inner_context.PrintIndent();
  516.         PrintString(key, context.out);
  517.         out << ": "sv;
  518.         PrintNode(node, inner_context);
  519.     }
  520.  
  521.     out.put('\n');
  522.     context.PrintIndent();
  523.     out.put('}');
  524. }
  525.  
  526. void PrintNode(const Node& node, const PrintContext& context) {
  527.     std::visit([&context](const auto& value) {
  528.             PrintValue(value, context);
  529.         },node.GetValue());
  530. }
  531.    
  532. void Print(const Document& document, std::ostream& output) {
  533.     PrintNode(document.GetRoot(), PrintContext{output});
  534. }
  535.  
  536. }//end namespace json
  537. -----------------------------------------------------------------------
  538. main.cpp
  539. -----------------------------------------------------------------------
  540. #include <cassert>
  541. #include <chrono>
  542. #include <sstream>
  543. #include <string_view>
  544.  
  545. #include "json.h"
  546.  
  547. using namespace json;
  548. using namespace std::literals;
  549.  
  550. namespace {
  551. json::Document LoadJSON(const std::string& s) {
  552.     std::istringstream strm(s);
  553.     return json::Load(strm);
  554. }
  555.  
  556. std::string Print(const Node& node) {
  557.     std::ostringstream out;
  558.     Print(Document{node}, out);
  559.     return out.str();
  560. }
  561.  
  562. void MustFailToLoad(const std::string& s) {
  563.     try {
  564.         LoadJSON(s);
  565.         std::cerr << "ParsingError exception is expected on '"sv << s << "'"sv << std::endl;
  566.         assert(false);
  567.     } catch (const json::ParsingError&) {
  568.         // ok
  569.     } catch (const std::exception& e) {
  570.         std::cerr << "exception thrown: "sv << e.what() << std::endl;
  571.         assert(false);
  572.     } catch (...) {
  573.         std::cerr << "Unexpected error"sv << std::endl;
  574.         assert(false);
  575.     }
  576. }
  577.  
  578. template <typename Fn>
  579. void MustThrowLogicError(Fn fn) {
  580.     try {
  581.         fn();
  582.         std::cerr << "logic_error is expected"sv << std::endl;
  583.         assert(false);
  584.     } catch (const std::logic_error&) {
  585.         // ok
  586.     } catch (const std::exception& e) {
  587.         std::cerr << "exception thrown: "sv << e.what() << std::endl;
  588.         assert(false);
  589.     } catch (...) {
  590.         std::cerr << "Unexpected error"sv << std::endl;
  591.         assert(false);
  592.     }
  593. }
  594.  
  595. void TestNull() {
  596.     Node null_node;
  597.     assert(null_node.IsNull());
  598.     assert(!null_node.IsInt());
  599.     assert(!null_node.IsDouble());
  600.     assert(!null_node.IsPureDouble());
  601.     assert(!null_node.IsString());
  602.     assert(!null_node.IsArray());
  603.     assert(!null_node.IsMap());
  604.  
  605.     Node null_node1{nullptr};
  606.     assert(null_node1.IsNull());
  607.  
  608.     assert(Print(null_node) == "null"s);
  609.     assert(null_node == null_node1);
  610.     assert(!(null_node != null_node1));
  611.  
  612.     const Node node = LoadJSON("null"s).GetRoot();
  613.     assert(node.IsNull());
  614.     assert(node == null_node);
  615.  
  616.     assert(LoadJSON(" \t\r\n\n\r null \t\r\n\n\r "s).GetRoot() == null_node);
  617. }
  618.  
  619. void TestNumbers() {
  620.     const Node int_node{42};
  621.     assert(int_node.IsInt());
  622.     assert(int_node.AsInt() == 42);
  623.  
  624.     assert(int_node.IsDouble());
  625.  
  626.     assert(int_node.AsDouble() == 42.0);
  627.     assert(!int_node.IsPureDouble());
  628.     assert(int_node == Node{42});
  629.  
  630.     assert(int_node != Node{42.0});
  631.  
  632.     const Node dbl_node{123.45};
  633.     assert(dbl_node.IsDouble());
  634.     assert(dbl_node.AsDouble() == 123.45);
  635.     assert(dbl_node.IsPureDouble());
  636.     assert(!dbl_node.IsInt());
  637.  
  638.     assert(Print(int_node) == "42"s);
  639.     assert(Print(dbl_node) == "123.45"s);
  640.     assert(Print(Node{-42}) == "-42"s);
  641.     assert(Print(Node{-3.5}) == "-3.5"s);
  642.  
  643.     assert(LoadJSON("42"s).GetRoot() == int_node);
  644.     assert(LoadJSON("123.45"s).GetRoot() == dbl_node);
  645.     assert(LoadJSON("0.25"s).GetRoot().AsDouble() == 0.25);
  646.     assert(LoadJSON("3e5"s).GetRoot().AsDouble() == 3e5);
  647.     assert(LoadJSON("1.2e-5"s).GetRoot().AsDouble() == 1.2e-5);
  648.     assert(LoadJSON("1.2e+5"s).GetRoot().AsDouble() == 1.2e5);
  649.     assert(LoadJSON("-123456"s).GetRoot().AsInt() == -123456);
  650.     assert(LoadJSON("0").GetRoot() == Node{0});
  651.     assert(LoadJSON("0.0").GetRoot() == Node{0.0});
  652.  
  653.     assert(LoadJSON(" \t\r\n\n\r 0.0 \t\r\n\n\r ").GetRoot() == Node{0.0});
  654. }
  655.  
  656. void TestStrings() {
  657.     Node str_node{"Hello, \"everybody\""s};
  658.     assert(str_node.IsString());
  659.     assert(str_node.AsString() == "Hello, \"everybody\""s);
  660.  
  661.     assert(!str_node.IsInt());
  662.     assert(!str_node.IsDouble());
  663.  
  664.     assert(Print(str_node) == "\"Hello, \\\"everybody\\\"\""s);
  665.  
  666.     assert(LoadJSON(Print(str_node)).GetRoot() == str_node);
  667.     const std::string escape_chars
  668.         = R"("\r\n\t\"\\")"s;
  669.  
  670.    assert(Print(LoadJSON(escape_chars).GetRoot()) == "\"\\r\\n\t\\\"\\\\\""s);
  671.     assert(LoadJSON("\t\r\n\n\r \"Hello\" \t\r\n\n\r ").GetRoot() == Node{"Hello"s});
  672. }
  673.  
  674. void TestBool() {
  675.     Node true_node{true};
  676.     assert(true_node.IsBool());
  677.     assert(true_node.AsBool());
  678.  
  679.     Node false_node{false};
  680.     assert(false_node.IsBool());
  681.     assert(!false_node.AsBool());
  682.  
  683.     assert(Print(true_node) == "true"s);
  684.     assert(Print(false_node) == "false"s);
  685.  
  686.     assert(LoadJSON("true"s).GetRoot() == true_node);
  687.     assert(LoadJSON("false"s).GetRoot() == false_node);
  688.     assert(LoadJSON(" \t\r\n\n\r true \r\n"s).GetRoot() == true_node);
  689.     assert(LoadJSON(" \t\r\n\n\r false \t\r\n\n\r "s).GetRoot() == false_node);
  690. }
  691.  
  692. void TestArray() {
  693.     Node arr_node{Array{1, 1.23, "Hello"s}};
  694.     assert(arr_node.IsArray());
  695.     const Array& arr = arr_node.AsArray();
  696.     assert(arr.size() == 3);
  697.     assert(arr.at(0).AsInt() == 1);
  698.  
  699.     assert(LoadJSON("[1,1.23,\"Hello\"]"s).GetRoot() == arr_node);
  700.     assert(LoadJSON(Print(arr_node)).GetRoot() == arr_node);
  701.     assert(LoadJSON(R"(  [ 1  ,  1.23,  "Hello"   ]   )"s).GetRoot() == arr_node);
  702.     assert(LoadJSON("[ 1 \r \n ,  \r\n\t 1.23, \n \n  \t\t  \"Hello\" \t \n  ] \n  "s).GetRoot()
  703.            == arr_node);
  704. }
  705.  
  706. void TestMap() {
  707.     Node dict_node{Dict{{"key1"s, "value1"s}, {"key2"s, 42}}};
  708.     assert(dict_node.IsMap());
  709.     const Dict& dict = dict_node.AsMap();
  710.     assert(dict.size() == 2);
  711.     assert(dict.at("key1"s).AsString() == "value1"s);
  712.     assert(dict.at("key2"s).AsInt() == 42);
  713.  
  714.     assert(LoadJSON("{ \"key1\": \"value1\", \"key2\": 42 }"s).GetRoot() == dict_node);
  715.     assert(LoadJSON(Print(dict_node)).GetRoot() == dict_node);
  716.     assert(
  717.         LoadJSON(
  718.             "\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)
  719.             .GetRoot()
  720.         == dict_node);
  721. }
  722.  
  723. void TestErrorHandling() {
  724.     MustFailToLoad("["s);
  725.     MustFailToLoad("]"s);
  726.  
  727.     MustFailToLoad("{"s);
  728.     MustFailToLoad("}"s);
  729.  
  730.     MustFailToLoad("\"hello"s);  // незакрытая кавычка
  731.  
  732.     MustFailToLoad("tru"s);
  733.     MustFailToLoad("fals"s);
  734.     MustFailToLoad("nul"s);
  735.  
  736.     Node dbl_node{3.5};
  737.     MustThrowLogicError([&dbl_node] {
  738.         dbl_node.AsInt();
  739.     });
  740.     MustThrowLogicError([&dbl_node] {
  741.         dbl_node.AsString();
  742.     });
  743.     MustThrowLogicError([&dbl_node] {
  744.         dbl_node.AsArray();
  745.     });
  746.  
  747.     Node array_node{Array{}};
  748.     MustThrowLogicError([&array_node] {
  749.         array_node.AsMap();
  750.     });
  751.     MustThrowLogicError([&array_node] {
  752.         array_node.AsDouble();
  753.     });
  754.     MustThrowLogicError([&array_node] {
  755.         array_node.AsBool();
  756.     });
  757. }
  758.  
  759. void Benchmark() {
  760.     const auto start = std::chrono::steady_clock::now();
  761.     Array arr;
  762.     arr.reserve(1'000);
  763.    for (int i = 0; i < 1'000; ++i) {
  764.         arr.emplace_back(Dict{
  765.             {"int"s, 42},
  766.             {"double"s, 42.1},
  767.             {"null"s, nullptr},
  768.             {"string"s, "hello"s},
  769.             {"array"s, Array{1, 2, 3}},
  770.             {"bool"s, true},
  771.             {"map"s, Dict{{"key"s, "value"s}}},
  772.         });
  773.     }
  774.     std::stringstream strm;
  775.     json::Print(Document{arr}, strm);
  776.     const auto doc = json::Load(strm);
  777.     assert(doc.GetRoot() == arr);
  778.     const auto duration = std::chrono::steady_clock::now() - start;
  779.     std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << "ms"sv
  780.               << std::endl;
  781. }
  782. }//end namespace
  783.  
  784. int main() {
  785.     TestNull();
  786.     TestNumbers();
  787.     TestStrings();
  788.     TestBool();
  789.     TestArray();
  790.     TestMap();
  791.     TestErrorHandling();
  792.     Benchmark();
  793. }
Add Comment
Please, Sign In to add comment