shushus

Спринт 12. Строим JSON. Задание 3.

Apr 16th, 2023 (edited)
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 82.51 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 transport_catalogue {
  13. namespace detail {
  14. namespace json {
  15.  
  16. class Node;
  17.  
  18. using Dict = std::map<std::string, Node>;
  19. using Array = std::vector<Node>;
  20.  
  21. class ParsingError : public std::runtime_error {
  22. public:
  23.     using runtime_error::runtime_error;
  24. };
  25.  
  26. class Node final : private std::variant<std::nullptr_t, Array, Dict, bool, int, double, std::string> {
  27. public:
  28.    
  29.     using variant::variant;
  30.     using Value = variant;
  31.  
  32.     Node() = default;
  33.     Node(bool value);
  34.     Node(Array array);
  35.     Node(Dict dict);
  36.     Node(int value);
  37.     Node(std::string value);
  38.     Node(std::nullptr_t);
  39.     Node(double value);
  40.    
  41.     const Array& as_array() const;
  42.     const Dict& as_dict() const;
  43.     int as_int() const;
  44.     double as_double() const;
  45.     bool as_bool() const;
  46.     const std::string& as_string() const;
  47.  
  48.     bool is_null() const;
  49.     bool is_int() const;
  50.     bool is_double() const;
  51.     bool is_real_double() const;
  52.     bool is_bool() const;
  53.     bool is_string() const;
  54.     bool is_array() const;
  55.     bool is_dict() const;
  56.  
  57.     const Value& get_value() const;
  58.        
  59. private:
  60.     Value value_;
  61. };
  62.  
  63. inline bool operator==(const Node& lhs, const Node& rhs) {
  64.     return lhs.get_value() == rhs.get_value();
  65. }  
  66. inline bool operator!=(const Node& lhs, const Node& rhs) {
  67.     return !(lhs == rhs);
  68. }
  69.    
  70. class Document {
  71. public:
  72.     Document() = default;
  73.     explicit Document(Node root);
  74.     const Node& get_root() const;
  75.  
  76. private:
  77.     Node root_;
  78. };
  79.  
  80. inline bool operator==(const Document& lhs, const Document& rhs) {
  81.     return lhs.get_root() == rhs.get_root();
  82. }
  83. inline bool operator!=(const Document& lhs, const Document& rhs) {
  84.     return !(lhs == rhs);
  85. }
  86.  
  87. Document load(std::istream& input);
  88. void print(const Document& document, std::ostream& output);
  89.  
  90. }//end namespace json
  91. }//end namespace detail
  92. }//end namespace transport_catalogue
  93. -----------------------------------------------------------------------
  94. json.cpp
  95. -----------------------------------------------------------------------
  96. #include "json.h"
  97.  
  98. using namespace std;
  99.  
  100. namespace transport_catalogue {
  101. namespace detail {
  102. namespace json {
  103. namespace {
  104.    
  105. Node load_node(istream& input);
  106.  
  107. std::string load_literal(std::istream& input) {
  108.     std::string str;
  109.    
  110.     while (std::isalpha(input.peek())) {
  111.         str.push_back(static_cast<char>(input.get()));
  112.     }
  113.     return str;
  114. }
  115.  
  116. Node load_array(std::istream& input) {
  117.     std::vector<Node> array;
  118.    
  119.     for (char ch; input >> ch && ch != ']';) {
  120.         if (ch != ',') {
  121.             input.putback(ch);
  122.         }
  123.        
  124.         array.push_back(load_node(input));
  125.     }
  126.  
  127.     if (!input) {
  128.         throw ParsingError("unable to parse array"s);
  129.     }
  130.  
  131.     return Node(array);
  132. }
  133.  
  134. Node load_null(std::istream& input) {
  135.     if (auto literal = load_literal(input); literal == "null"sv) {
  136.         return Node(nullptr);
  137.     } else {
  138.         throw ParsingError("unable to parse '"s + literal + "' as null"s);
  139.     }
  140. }
  141.  
  142. Node load_bool(std::istream& input) {
  143.     const auto str = load_literal(input);
  144.  
  145.     if (str == "true"sv) {
  146.         return Node(true);
  147.     } else if (str == "false"sv) {
  148.         return Node(false);
  149.     } else {
  150.         throw ParsingError("unable to parse '"s + str + "' as bool"s);
  151.     }
  152. }
  153.  
  154. Node load_number(std::istream& input) {
  155.     std::string number;
  156.  
  157.     auto read_char = [&number, &input] {
  158.         number += static_cast<char>(input.get());
  159.        
  160.         if (!input) {
  161.             throw ParsingError("unable to read number"s);
  162.         }
  163.     };
  164.  
  165.     auto read_digits = [&input, read_char] {
  166.        
  167.         if (!std::isdigit(input.peek())) {
  168.             throw ParsingError("digit expected"s);
  169.         } else {
  170.             while (std::isdigit(input.peek())) {
  171.                 read_char();
  172.             }  
  173.         }
  174.     };
  175.  
  176.     if (input.peek() == '-') {
  177.         read_char();
  178.     }
  179.  
  180.     if (input.peek() == '0') {
  181.         read_char();
  182.     } else {
  183.         read_digits();
  184.     }
  185.  
  186.     bool is_int = true;
  187.     if (input.peek() == '.') {
  188.         read_char();
  189.         read_digits();
  190.         is_int = false;
  191.     }
  192.  
  193.     if (int ch = input.peek(); ch == 'e' || ch == 'E') {
  194.         read_char();
  195.        
  196.         if (ch = input.peek(); ch == '+' || ch == '-') {
  197.             read_char();
  198.         }
  199.  
  200.         read_digits();
  201.         is_int = false;
  202.     }
  203.  
  204.     try {
  205.         if (is_int) {
  206.             try {
  207.                 return Node(std::stoi(number));
  208.                
  209.             } catch (...) {}
  210.         }
  211.         return Node(std::stod(number));
  212.        
  213.     } catch (...) {
  214.         throw ParsingError("unable to convert "s + number + " to number"s);
  215.     }
  216. }
  217.  
  218. Node load_string(std::istream& input) {
  219.     auto it = std::istreambuf_iterator<char>(input);
  220.     auto end = std::istreambuf_iterator<char>();
  221.     std::string str;
  222.    
  223.     while (true) {
  224.         if (it == end) {
  225.             throw ParsingError("unable to parse string");
  226.         }
  227.        
  228.         const char ch = *it;
  229.         if (ch == '"') {
  230.             ++it;
  231.             break;
  232.            
  233.         } else if (ch == '\\') {
  234.             ++it;
  235.             if (it == end) {
  236.                 throw ParsingError("unable to parse string");
  237.             }
  238.            
  239.             const char esc_ch = *(it);
  240.             switch (esc_ch) {
  241.                 case 'n':
  242.                     str.push_back('\n');
  243.                     break;
  244.                 case 't':
  245.                     str.push_back('\t');
  246.                     break;
  247.                 case 'r':
  248.                     str.push_back('\r');
  249.                     break;
  250.                 case '"':
  251.                     str.push_back('"');
  252.                     break;
  253.                 case '\\':
  254.                     str.push_back('\\');
  255.                     break;
  256.                 default:
  257.                     throw ParsingError("invalid esc \\"s + esc_ch);
  258.             }
  259.            
  260.         } else if (ch == '\n' || ch == '\r') {
  261.             throw ParsingError("invalid line end"s);
  262.         } else {
  263.             str.push_back(ch);
  264.         }
  265.        
  266.         ++it;
  267.     }
  268.    
  269.     return Node(str);
  270. }
  271.    
  272. Node load_dictionary(std::istream& input) {
  273.     Dict dictionary;
  274.  
  275.     for (char ch; input >> ch && ch != '}';) {
  276.        
  277.         if (ch == '"') {
  278.             std::string key = load_string(input).as_string();
  279.  
  280.             if (input >> ch && ch == ':') {
  281.                
  282.                 if (dictionary.find(key) != dictionary.end()) {
  283.                     throw ParsingError("duplicate key '"s + key + "'found");
  284.                 }
  285.  
  286.                 dictionary.emplace(std::move(key), load_node(input));
  287.                
  288.             } else {
  289.                 throw ParsingError(": expected. but '"s + ch + "' found"s);
  290.             }
  291.            
  292.         } else if (ch != ',') {
  293.             throw ParsingError("',' expected. but '"s + ch + "' found"s);
  294.         }
  295.     }
  296.  
  297.     if (!input) {
  298.         throw ParsingError("unable to parse dictionary"s);
  299.     } else {
  300.         return Node(dictionary);
  301.     }
  302.    
  303. }
  304.  
  305. Node load_node(std::istream& input) {
  306.     char ch;
  307.    
  308.     if (!(input >> ch)) {
  309.         throw ParsingError(""s);
  310.     } else {
  311.         switch (ch) {
  312.         case '[':
  313.             return load_array(input);
  314.         case '{':
  315.             return load_dictionary(input);
  316.         case '"':
  317.             return load_string(input);
  318.         case 't': case 'f':
  319.             input.putback(ch);
  320.             return load_bool(input);
  321.         case 'n':
  322.             input.putback(ch);
  323.             return load_null(input);
  324.         default:
  325.             input.putback(ch);
  326.             return load_number(input);
  327.         }
  328.     }
  329. }
  330.    
  331. }//end namespace
  332.    
  333. Node::Node(Array array) : value_(std::move(array)) {}    
  334. Node::Node(std::nullptr_t) : Node() {}
  335. Node::Node(bool value) : value_(value) {}
  336. Node::Node(Dict dict) : value_(std::move(dict)) {}
  337. Node::Node(int value) : value_(value) {}
  338. Node::Node(string value) : value_(std::move(value)) {}
  339. Node::Node(double value) : value_(value) {}
  340.    
  341. const Array& Node::as_array() const {
  342.     using namespace std::literals;
  343.    
  344.     if (!is_array()) {
  345.         throw std::logic_error("value is not an array"s);
  346.     } else {
  347.         return std::get<Array>(value_);
  348.     }
  349. }
  350.  
  351. const Dict& Node::as_dict() const {
  352.     using namespace std::literals;
  353.    
  354.     if (!is_dict()) {
  355.         throw std::logic_error("value is not a dictionary"s);
  356.     } else {
  357.         return std::get<Dict>(value_);  
  358.     }
  359. }
  360.  
  361. const std::string& Node::as_string() const {
  362.     using namespace std::literals;
  363.    
  364.     if (!is_string()) {
  365.         throw std::logic_error("value is not a string"s);
  366.     } else {
  367.         return std::get<std::string>(value_);        
  368.     }
  369. }
  370.    
  371. int Node::as_int() const {
  372.     using namespace std::literals;
  373.    
  374.     if (!is_int()) {
  375.         throw std::logic_error("value is not an int"s);
  376.     } else {
  377.         return std::get<int>(value_);    
  378.     }
  379. }
  380.  
  381. double Node::as_double() const {
  382.     using namespace std::literals;
  383.    
  384.     if (!is_double()) {
  385.         throw std::logic_error("value is not a double"s);
  386.     } else if (is_real_double()) {
  387.         return std::get<double>(value_);
  388.     } else {
  389.         return as_int();
  390.     }  
  391. }
  392.  
  393. bool Node::as_bool() const {
  394.     using namespace std::literals;
  395.    
  396.     if (!is_bool()) {
  397.         throw std::logic_error("value is not a bool"s);
  398.     } else {
  399.         return std::get<bool>(value_);  
  400.     }
  401. }
  402.    
  403. bool Node::is_null() const {return std::holds_alternative<std::nullptr_t>(value_);}
  404. bool Node::is_int() const {return std::holds_alternative<int>(value_);}
  405. bool Node::is_double() const {return is_real_double() || is_int();}  
  406. bool Node::is_real_double() const {return std::holds_alternative<double>(value_);}
  407. bool Node::is_bool() const {return std::holds_alternative<bool>(value_);}
  408. bool Node::is_string() const {return std::holds_alternative<std::string>(value_);}
  409. bool Node::is_array() const {return std::holds_alternative<Array>(value_);}
  410. bool Node::is_dict() const {return std::holds_alternative<Dict>(value_);}
  411.  
  412. const Node::Value& Node::get_value() const {return value_;}
  413.    
  414. Document::Document(Node root) : root_(std::move(root)) {}
  415. const Node& Document::get_root() const {return root_;}
  416.    
  417. Document load(istream& input) {return Document(load_node(input));}
  418.  
  419. struct PrintContext {
  420.     std::ostream& out;
  421.     int indent_step = 4;
  422.     int indent = 0;
  423.  
  424.     void print_indent() const {
  425.         for (int i = 0; i < indent; ++i) {
  426.             out.put(' ');
  427.         }
  428.     }
  429.  
  430.     [[nodiscard]] PrintContext indented() const {
  431.         return {out,
  432.                 indent_step,
  433.                 indent_step + indent};
  434.     }
  435. };
  436.  
  437. void print_node(const Node& node, const PrintContext& context);
  438.  
  439. void print_string(const std::string& value, std::ostream& out) {
  440.     out.put('"');
  441.    
  442.     for (const char ch : value) {
  443.         switch (ch) {
  444.             case '\r':
  445.                 out << R"(\r)";
  446.                 break;
  447.             case '\n':
  448.                 out << R"(\n)";
  449.                 break;
  450.             case '"':
  451.                 out << R"(\")";
  452.                 break;
  453.             case '\\':
  454.                 out << R"(\\)";
  455.                 break;
  456.             default:
  457.                 out.put(ch);
  458.                 break;
  459.         }
  460.     }
  461.    
  462.     out.put('"');
  463. }
  464.  
  465. template <typename Value>
  466. void print_value(const Value& value, const PrintContext& context) {
  467.     context.out << value;
  468. }    
  469.  
  470. template <>
  471. void print_value<std::string>(const std::string& value, const PrintContext& context) {
  472.     print_string(value, context.out);
  473. }
  474.  
  475. void print_value(const std::nullptr_t&, const PrintContext& context) {
  476.     context.out << "null"s;
  477. }
  478.  
  479. void print_value(bool value, const PrintContext& context) {
  480.     context.out << std::boolalpha << value;
  481. }
  482.  
  483. [[maybe_unused]] void print_value(Array nodes, const PrintContext& context) {
  484.     std::ostream& out = context.out;
  485.     out << "[\n"sv;
  486.     bool first = true;
  487.     auto inner_context = context.indented();
  488.    
  489.     for (const Node& node : nodes) {
  490.         if (first) {
  491.             first = false;
  492.         } else {
  493.             out << ",\n"sv;
  494.         }
  495.  
  496.         inner_context.print_indent();
  497.         print_node(node, inner_context);
  498.     }
  499.  
  500.     out.put('\n');
  501.     context.print_indent();
  502.     out.put(']');
  503. }
  504.  
  505. [[maybe_unused]] void print_value(Dict nodes, const PrintContext& context) {
  506.     std::ostream& out = context.out;
  507.     out << "{\n"sv;
  508.     bool first = true;
  509.     auto inner_context = context.indented();
  510.    
  511.     for (const auto& [key, node] : nodes) {
  512.         if (first) {
  513.             first = false;
  514.         } else {
  515.             out << ",\n"sv;
  516.         }
  517.  
  518.         inner_context.print_indent();
  519.         print_string(key, context.out);
  520.         out << ": "sv;
  521.         print_node(node, inner_context);
  522.     }
  523.  
  524.     out.put('\n');
  525.     context.print_indent();
  526.     out.put('}');
  527. }
  528.  
  529. void print_node(const Node& node, const PrintContext& context) {
  530.     std::visit([&context](const auto& value) {
  531.             print_value(value, context);
  532.         }, node.get_value());
  533. }
  534.    
  535. void print(const Document& document, std::ostream& output) {
  536.     print_node(document.get_root(), PrintContext{output});
  537. }
  538.  
  539. }//end namespace json
  540. }//end namespace detail
  541. }//end namespace transport_catalogue
  542. -----------------------------------------------------------------------
  543. json_builder.h
  544. -----------------------------------------------------------------------
  545. #pragma once
  546.  
  547. #include "json.h"
  548. #include <stack>
  549. #include <string>
  550. #include <memory>
  551.  
  552. namespace transport_catalogue {
  553. namespace detail {
  554. namespace json {
  555. namespace builder {
  556.  
  557. class KeyContext;
  558. class DictionaryContext;
  559. class ArrayContext;
  560.  
  561. class Builder {
  562. public:
  563.     Node make_node(const Node::Value& value_);
  564.     void add_node(const Node& node);
  565.  
  566.     KeyContext key(const std::string& key_);
  567.     Builder& value(const Node::Value& value);
  568.    
  569.     DictionaryContext start_dict();
  570.     Builder& end_dict();
  571.    
  572.     ArrayContext start_array();
  573.     Builder& end_array();
  574.  
  575.     Node build();
  576.  
  577. private:
  578.     Node root_;
  579.     std::vector<std::unique_ptr<Node>> nodes_stack_;
  580.  
  581. };
  582.  
  583. class BaseContext {
  584. public:
  585.     BaseContext(Builder& builder);
  586.  
  587.     KeyContext key(const std::string& key);
  588.     Builder& value(const Node::Value& value);
  589.    
  590.     DictionaryContext start_dict();
  591.     Builder& end_dict();
  592.    
  593.     ArrayContext start_array();
  594.     Builder& end_array();
  595.  
  596. protected:
  597.     Builder& builder_;
  598.  
  599. };
  600.  
  601. class KeyContext : public BaseContext {
  602. public:
  603.     KeyContext(Builder& builder);
  604.  
  605.     KeyContext key(const std::string& key) = delete;
  606.  
  607.     BaseContext end_dict() = delete;
  608.     BaseContext end_array() = delete;
  609.  
  610.     DictionaryContext value(const Node::Value& value);
  611. };
  612.  
  613. class DictionaryContext : public BaseContext {
  614. public:
  615.     DictionaryContext(Builder& builder);
  616.  
  617.     DictionaryContext start_dict() = delete;
  618.  
  619.     ArrayContext start_array() = delete;
  620.     Builder& end_array() = delete;
  621.  
  622.     Builder& value(const Node::Value& value) = delete;
  623. };
  624.  
  625. class ArrayContext : public BaseContext {
  626. public:
  627.     ArrayContext(Builder& builder);
  628.  
  629.     KeyContext key(const std::string& key) = delete;
  630.  
  631.     Builder& end_dict() = delete;
  632.  
  633.     ArrayContext value(const Node::Value& value);
  634. };
  635.  
  636. }//end namespace builder
  637. }//end namespace json
  638. }//end namespace detail
  639. }//end namespace transport_catalogue
  640. -----------------------------------------------------------------------
  641. json_builder.cpp
  642. -----------------------------------------------------------------------
  643. #include "json_builder.h"
  644.  
  645. namespace transport_catalogue {
  646. namespace detail {
  647. namespace json {
  648. namespace builder {
  649.  
  650. //---------------------BaseContext---------------------
  651.  
  652. BaseContext::BaseContext(Builder& builder) : builder_(builder) {}
  653.  
  654. KeyContext BaseContext::key(const std::string& key) {return builder_.key(key);}
  655. Builder& BaseContext::value(const Node::Value& value) {return builder_.value(value);}
  656.  
  657. DictionaryContext BaseContext::start_dict() {return DictionaryContext(builder_.start_dict());}
  658. Builder& BaseContext::end_dict() {return builder_.end_dict();}
  659.  
  660. ArrayContext BaseContext::start_array() {return ArrayContext(builder_.start_array());}
  661. Builder& BaseContext::end_array() {return builder_.end_array();}
  662.    
  663. //---------------------KeyContext-----------------------
  664.  
  665. KeyContext::KeyContext(Builder& builder) : BaseContext(builder) {}
  666.  
  667. DictionaryContext KeyContext::value(const Node::Value& value) {return BaseContext::value(std::move(value));}
  668.    
  669. //---------------------DictionaryContext----------------
  670.  
  671. DictionaryContext::DictionaryContext(Builder& builder) : BaseContext(builder) {}
  672.  
  673. //---------------------ArrayContext---------------------
  674.  
  675. ArrayContext::ArrayContext(Builder& builder) : BaseContext(builder) {}
  676.  
  677. ArrayContext ArrayContext::value(const Node::Value& value) {return BaseContext::value(std::move(value)); }
  678.  
  679. //---------------------Builder--------------------------
  680.  
  681. Node Builder::make_node(const Node::Value& value_) {
  682.     Node node;
  683.  
  684.     if (std::holds_alternative<bool>(value_)) {
  685.         bool bol = std::get<bool>(value_);
  686.         node = Node(bol);
  687.  
  688.     } else if (std::holds_alternative<int>(value_)) {
  689.         int intt = std::get<int>(value_);
  690.         node = Node(intt);
  691.  
  692.     } else if (std::holds_alternative<double>(value_)) {
  693.         double doble = std::get<double>(value_);
  694.         node = Node(doble);
  695.  
  696.     } else if (std::holds_alternative<std::string>(value_)) {
  697.         std::string str = std::get<std::string>(value_);
  698.         node = Node(std::move(str));
  699.  
  700.     } else if (std::holds_alternative<Array>(value_)) {
  701.         Array arr = std::get<Array>(value_);
  702.         node = Node(std::move(arr));
  703.  
  704.     } else if (std::holds_alternative<Dict>(value_)) {
  705.         Dict dictionary = std::get<Dict>(value_);
  706.         node = Node(std::move(dictionary));
  707.  
  708.     } else {
  709.         node = Node();
  710.     }
  711.  
  712.     return node;
  713. }
  714.  
  715. void Builder::add_node(const Node& node) {
  716.     if (nodes_stack_.empty()) {
  717.  
  718.         if (!root_.is_null()) {
  719.             throw std::logic_error("root has been added");
  720.         }
  721.  
  722.         root_ = node;
  723.         return;
  724.  
  725.     } else {
  726.  
  727.         if (!nodes_stack_.back()->is_array()
  728.             && !nodes_stack_.back()->is_string()) {
  729.  
  730.             throw std::logic_error("unable to create node");
  731.         }
  732.  
  733.         if (nodes_stack_.back()->is_array()) {
  734.             Array arr = nodes_stack_.back()->as_array();
  735.             arr.emplace_back(node);
  736.  
  737.             nodes_stack_.pop_back();
  738.             auto arr_ptr = std::make_unique<Node>(arr);
  739.             nodes_stack_.emplace_back(std::move(arr_ptr));
  740.  
  741.             return;
  742.         }
  743.  
  744.         if (nodes_stack_.back()->is_string()) {
  745.             std::string str = nodes_stack_.back()->as_string();
  746.             nodes_stack_.pop_back();
  747.  
  748.             if (nodes_stack_.back()->is_dict()) {
  749.                 Dict dictionary = nodes_stack_.back()->as_dict();
  750.                 dictionary.emplace(std::move(str), node);
  751.  
  752.                 nodes_stack_.pop_back();
  753.                 auto dictionary_ptr = std::make_unique<Node>(dictionary);
  754.                 nodes_stack_.emplace_back(std::move(dictionary_ptr));
  755.             }
  756.  
  757.             return;
  758.         }
  759.     }
  760. }
  761.  
  762. KeyContext Builder::key(const std::string& key_) {
  763.     if (nodes_stack_.empty()) {
  764.         throw std::logic_error("unable to create key");
  765.     }
  766.  
  767.     auto key_ptr = std::make_unique<Node>(key_);
  768.  
  769.     if (nodes_stack_.back()->is_dict()) {
  770.         nodes_stack_.emplace_back(std::move(key_ptr));
  771.     }
  772.  
  773.     return KeyContext(*this);
  774. }
  775.  
  776. Builder& Builder::value(const Node::Value& value_) {
  777.     add_node(make_node(value_));
  778.  
  779.     return *this;
  780. }
  781.  
  782. DictionaryContext Builder::start_dict() {
  783.     nodes_stack_.emplace_back(std::move(std::make_unique<Node>(Dict())));
  784.  
  785.     return DictionaryContext(*this);
  786. }
  787.  
  788. Builder& Builder::end_dict() {
  789.     if (nodes_stack_.empty()) {
  790.         throw std::logic_error("unable to close as without opening");
  791.     }
  792.  
  793.     Node node = *nodes_stack_.back();
  794.  
  795.     if (!node.is_dict()) {
  796.         throw std::logic_error("object isn't dictionary");
  797.     }
  798.  
  799.     nodes_stack_.pop_back();
  800.     add_node(node);
  801.  
  802.     return *this;
  803. }
  804.  
  805. ArrayContext Builder::start_array() {
  806.     nodes_stack_.emplace_back(std::move(std::make_unique<Node>(Array())));
  807.  
  808.     return ArrayContext(*this);
  809. }
  810.  
  811. Builder& Builder::end_array() {
  812.     if (nodes_stack_.empty()) {
  813.         throw std::logic_error("unable to close without opening");
  814.     }
  815.  
  816.     Node node = *nodes_stack_.back();
  817.  
  818.     if (!node.is_array()) {
  819.         throw std::logic_error("object isn't array");
  820.     }
  821.  
  822.     nodes_stack_.pop_back();
  823.     add_node(node);
  824.  
  825.     return *this;
  826. }
  827.  
  828. Node Builder::build() {
  829.     if (root_.is_null()) {
  830.         throw std::logic_error("empty json");
  831.     }
  832.  
  833.     if (!nodes_stack_.empty()) {
  834.         throw std::logic_error("invalid json");
  835.     }
  836.  
  837.     return root_;
  838. }
  839.  
  840. }//end namespace builder
  841. }//end namespace json
  842. }//end namespace detail
  843. }//end namespace transport_catalogue
  844. -----------------------------------------------------------------------
  845. main.cpp
  846. -----------------------------------------------------------------------
  847. #include "json_reader.h"
  848. #include "map_renderer.h"
  849. #include "request_handler.h"
  850.  
  851. using namespace std;
  852. using namespace transport_catalogue;
  853. using namespace map_renderer;
  854. using namespace request_handler;
  855. using namespace transport_catalogue::detail::json;
  856.  
  857. int main() {
  858.     vector<StatRequest> stat_request;
  859.     RenderSettings render_settings;
  860.     TransportCatalogue catalogue;  
  861.      
  862.     JSONReader json_reader;
  863.     RequestHandler request_handler;
  864.        
  865.     json_reader = JSONReader(cin);    
  866.     json_reader.parse(catalogue, stat_request, render_settings);
  867.    
  868.     request_handler = RequestHandler();    
  869.     request_handler.execute_queries(catalogue, stat_request, render_settings);
  870.     transport_catalogue::detail::json::print(request_handler.get_document(), cout);
  871. }
  872.  
  873. -----------------------------------------------------------------------
  874. domain.cpp
  875. -----------------------------------------------------------------------
  876.  
  877. empty
  878.  
  879. -----------------------------------------------------------------------
  880. domain.h
  881. -----------------------------------------------------------------------
  882. #pragma once
  883.  
  884. #include <algorithm>
  885. #include <vector>
  886. #include <string>
  887.  
  888. #include "geo.h"
  889.  
  890. namespace domain {
  891.  
  892. struct StatRequest {
  893.     int id;
  894.     std::string type;
  895.     std::string name;    
  896. };
  897.    
  898. struct Bus;
  899.    
  900. struct Stop {    
  901.     std::string name;
  902.     double latitude;
  903.     double longitude;
  904.    
  905.     std::vector<Bus*> buses;
  906. };
  907.  
  908. struct Bus {
  909.     std::string name;
  910.     std::vector<Stop*> stops;
  911.     bool is_roundtrip;
  912.     size_t route_length;
  913. };
  914.  
  915. struct Distance {    
  916.     const Stop* start;
  917.     const Stop* end;
  918.     int distance;
  919. };  
  920.  
  921. struct BusQueryResult {
  922.     std::string_view name;
  923.     bool not_found;
  924.     int stops_on_route;
  925.     int unique_stops;
  926.     int route_length;
  927.     double curvature;
  928. };    
  929.    
  930. struct StopQueryResult {
  931.     std::string_view name;
  932.     bool not_found;
  933.     std::vector <std::string> buses_name;
  934. };
  935.  
  936. }//end namespace domain
  937. -----------------------------------------------------------------------
  938. geo.cpp
  939. -----------------------------------------------------------------------
  940. #define _USE_MATH_DEFINES
  941. #include "geo.h"
  942.  
  943. #include <cmath>
  944.  
  945. namespace geo {
  946.    
  947. double compute_distance(Coordinates start, Coordinates end) {
  948.     using namespace std;
  949.    
  950.     if (!(start == end)) {
  951.         const double dr = PI / 180.;
  952.         return acos(sin(start.latitude * dr) * sin(end.latitude * dr)
  953.                     + cos(start.latitude * dr) * cos(end.latitude * dr)
  954.                     * cos(abs(start.longitude - end.longitude) * dr)) * EARTH_RADIUS;
  955.     } else {
  956.         return 0.0;
  957.     }
  958. }
  959.    
  960. }//end namespace geo
  961. -----------------------------------------------------------------------
  962. geo.h
  963. -----------------------------------------------------------------------
  964. #pragma once
  965. #include <cmath>
  966.  
  967. namespace geo {
  968.    
  969. const int EARTH_RADIUS = 6371000;
  970. const double PI = 3.1415926535;
  971.    
  972. struct Coordinates {
  973.     double latitude;
  974.     double longitude;
  975.  
  976.     bool operator==(const Coordinates& other) const {
  977.         return latitude == other.latitude && longitude == other.longitude;
  978.     }
  979.     bool operator!=(const Coordinates& other) const {
  980.         return !(*this == other);
  981.     }
  982. };
  983.    
  984. double compute_distance(Coordinates start, Coordinates end);
  985.    
  986. }//end namespace geo
  987. -----------------------------------------------------------------------
  988. json_reader.cpp
  989. -----------------------------------------------------------------------
  990. #include "json_reader.h"
  991.  
  992. namespace transport_catalogue {
  993. namespace detail {
  994. namespace json {
  995.    
  996. JSONReader::JSONReader(Document doc) : document_(std::move(doc)) {}
  997. JSONReader::JSONReader(std::istream& input) : document_(json::load(input)) {}    
  998.    
  999. Stop JSONReader::parse_node_stop(Node& node) {
  1000.     Stop stop;
  1001.     Dict stop_node;
  1002.    
  1003.     if (node.is_dict()) {
  1004.         stop_node = node.as_dict();
  1005.         stop.name = stop_node.at("name").as_string();
  1006.         stop.latitude = stop_node.at("latitude").as_double();
  1007.         stop.longitude = stop_node.at("longitude").as_double();
  1008.     }
  1009.    
  1010.     return stop;
  1011. }
  1012.    
  1013. std::vector<Distance> JSONReader::parse_node_distances(Node& node, TransportCatalogue& catalogue) {
  1014.     std::vector<Distance> distances;
  1015.     Dict stop_node;
  1016.     Dict stop_road_map;
  1017.     std::string begin_name;
  1018.     std::string last_name;
  1019.     int distance;
  1020.    
  1021.     if (node.is_dict()) {
  1022.         stop_node = node.as_dict();
  1023.         begin_name = stop_node.at("name").as_string();
  1024.        
  1025.         try {
  1026.             stop_road_map = stop_node.at("road_distances").as_dict();
  1027.            
  1028.             for (auto [key, value] : stop_road_map) {
  1029.                 last_name = key;
  1030.                 distance = value.as_int();
  1031.                 distances.push_back({catalogue.get_stop(begin_name),
  1032.                                      catalogue.get_stop(last_name), distance});
  1033.             }
  1034.            
  1035.         } catch(...) {
  1036.             std::cout << "invalide road" << std::endl;
  1037.         }        
  1038.     }
  1039.    
  1040.     return distances;
  1041. }
  1042.  
  1043. Bus JSONReader::parse_node_bus(Node& node, TransportCatalogue& catalogue) {
  1044.     Bus bus;
  1045.     Dict bus_node;
  1046.     Array bus_stops;
  1047.    
  1048.     if (node.is_dict()) {
  1049.         bus_node = node.as_dict();
  1050.         bus.name = bus_node.at("name").as_string();
  1051.         bus.is_roundtrip = bus_node.at("is_roundtrip").as_bool();
  1052.  
  1053.         try {
  1054.             bus_stops = bus_node.at("stops").as_array();
  1055.            
  1056.             for (Node stop : bus_stops) {
  1057.                 bus.stops.push_back(catalogue.get_stop(stop.as_string()));
  1058.             }
  1059.  
  1060.             if (!bus.is_roundtrip) {
  1061.                 size_t size = bus.stops.size() - 1;
  1062.                
  1063.                 for (size_t i = size; i > 0; i--) {
  1064.                     bus.stops.push_back(bus.stops[i-1]);
  1065.                 }
  1066.                
  1067.             }
  1068.            
  1069.         } catch(...) {
  1070.             std::cout << "base_requests: bus: stops is empty" << std::endl;
  1071.         }        
  1072.     }
  1073.    
  1074.     return bus;
  1075. }
  1076.    
  1077. void JSONReader::parse_node_base(const Node& root, TransportCatalogue& catalogue){
  1078.     Array base_requests;
  1079.     Dict req_map;
  1080.     Node req_node;
  1081.    
  1082.     std::vector<Node> buses;
  1083.     std::vector<Node> stops;
  1084.    
  1085.     if (root.is_array()) {
  1086.         base_requests = root.as_array();
  1087.        
  1088.         for (Node& node : base_requests) {            
  1089.             if (node.is_dict()) {
  1090.                 req_map = node.as_dict();
  1091.                
  1092.                 try {
  1093.                     req_node = req_map.at("type");
  1094.                    
  1095.                     if (req_node.is_string()) {
  1096.                        
  1097.                         if (req_node.as_string() == "Bus") {
  1098.                             buses.push_back(req_map);
  1099.                         } else if (req_node.as_string() == "Stop") {
  1100.                             stops.push_back(req_map);
  1101.                         } else {
  1102.                             std::cout << "base_requests are invalid";
  1103.                         }
  1104.                     }
  1105.                    
  1106.                 } catch(...) {
  1107.                     std::cout << "base_requests does not have type value";
  1108.                 }                
  1109.             }
  1110.         }  
  1111.        
  1112.         for (auto stop : stops) {
  1113.             catalogue.add_stop(parse_node_stop(stop));
  1114.         }
  1115.        
  1116.         for (auto stop : stops) {
  1117.             catalogue.add_distance(parse_node_distances(stop, catalogue));
  1118.         }
  1119.        
  1120.         for (auto bus : buses) {
  1121.             catalogue.add_bus(parse_node_bus(bus, catalogue));
  1122.         }
  1123.        
  1124.     } else {
  1125.         std::cout << "base_requests is not an array";
  1126.     }  
  1127. }
  1128.  
  1129. void JSONReader::parse_node_stat(const Node& node, std::vector<StatRequest>& stat_request){
  1130.     Array stat_requests;
  1131.     Dict req_map;
  1132.     StatRequest req;
  1133.    
  1134.     if (node.is_array()) {
  1135.         stat_requests = node.as_array();
  1136.        
  1137.         for (Node req_node : stat_requests) {
  1138.            
  1139.             if (req_node.is_dict()) {
  1140.                 req_map = req_node.as_dict();
  1141.                 req.id = req_map.at("id").as_int();
  1142.                 req.type = req_map.at("type").as_string();
  1143.  
  1144.                 if (req.type != "Map") {
  1145.                     req.name = req_map.at("name").as_string();
  1146.                 } else {
  1147.                     req.name = "";
  1148.                 }
  1149.                
  1150.                 stat_request.push_back(req);
  1151.                
  1152.             }  
  1153.         }
  1154.        
  1155.     } else {
  1156.         std::cout << "base_requests is not array";
  1157.     }
  1158. }
  1159.  
  1160. void JSONReader::parse_node_render(const Node& node, map_renderer::RenderSettings& rend_set){
  1161.     Dict rend_map;
  1162.     Array bus_lab_offset;
  1163.     Array stop_lab_offset;
  1164.     Array arr_color;
  1165.     Array arr_palette;
  1166.     uint8_t red_;
  1167.     uint8_t green_;
  1168.     uint8_t blue_;
  1169.     double opacity_;
  1170.  
  1171.     if (node.is_dict()) {
  1172.         rend_map = node.as_dict();
  1173.        
  1174.         try {
  1175.             rend_set.width_ = rend_map.at("width").as_double();
  1176.             rend_set.height_ = rend_map.at("height").as_double();
  1177.             rend_set.padding_ = rend_map.at("padding").as_double();
  1178.             rend_set.line_width_ = rend_map.at("line_width").as_double();
  1179.             rend_set.stop_radius_ = rend_map.at("stop_radius").as_double();
  1180.            
  1181.             rend_set.bus_label_font_size_ = rend_map.at("bus_label_font_size").as_int();
  1182.            
  1183.             if (rend_map.at("bus_label_offset").is_array()) {
  1184.                 bus_lab_offset = rend_map.at("bus_label_offset").as_array();
  1185.                 rend_set.bus_label_offset_ = std::make_pair(bus_lab_offset[0].as_double(),
  1186.                                                             bus_lab_offset[1].as_double());
  1187.             }
  1188.            
  1189.             rend_set.stop_label_font_size_ = rend_map.at("stop_label_font_size").as_int();
  1190.  
  1191.             if (rend_map.at("stop_label_offset").is_array()) {
  1192.                 stop_lab_offset = rend_map.at("stop_label_offset").as_array();
  1193.                 rend_set.stop_label_offset_ = std::make_pair(stop_lab_offset[0].as_double(),
  1194.                                                              stop_lab_offset[1].as_double());
  1195.             }
  1196.            
  1197.             if (rend_map.at("underlayer_color").is_string()) {
  1198.                 rend_set.underlayer_color_ = svg::Color(rend_map.at("underlayer_color").as_string());
  1199.             } else if (rend_map.at("underlayer_color").is_array()) {
  1200.                 arr_color = rend_map.at("underlayer_color").as_array();
  1201.                 red_ = arr_color[0].as_int();
  1202.                 green_ = arr_color[1].as_int();
  1203.                 blue_ = arr_color[2].as_int();
  1204.  
  1205.                 if(arr_color.size() == 4){
  1206.                     opacity_ = arr_color[3].as_double();
  1207.                     rend_set.underlayer_color_ = svg::Color(svg::Rgba(red_,
  1208.                                                                       green_,
  1209.                                                                       blue_,
  1210.                                                                       opacity_));
  1211.                 } else if (arr_color.size() == 3) {
  1212.                     rend_set.underlayer_color_ = svg::Color(svg::Rgb(red_,
  1213.                                                                      green_,
  1214.                                                                      blue_));
  1215.                 }
  1216.                
  1217.             }
  1218.  
  1219.             rend_set.underlayer_width_ = rend_map.at("underlayer_width").as_double();
  1220.  
  1221.             if (rend_map.at("color_palette").is_array()) {
  1222.                 arr_palette = rend_map.at("color_palette").as_array();
  1223.                
  1224.                 for (Node color_palette : arr_palette) {
  1225.                    
  1226.                     if (color_palette.is_string()) {
  1227.                         rend_set.color_palette_.push_back(svg::Color(color_palette.as_string()));
  1228.                     } else if (color_palette.is_array()) {
  1229.                         arr_color = color_palette.as_array();
  1230.                         red_ = arr_color[0].as_int();
  1231.                         green_ = arr_color[1].as_int();
  1232.                         blue_ = arr_color[2].as_int();
  1233.  
  1234.                         if (arr_color.size() == 4) {
  1235.                             opacity_ = arr_color[3].as_double();
  1236.                             rend_set.color_palette_.push_back(svg::Color(svg::Rgba(red_,
  1237.                                                                                    green_,
  1238.                                                                                    blue_,
  1239.                                                                                    opacity_)));
  1240.                         } else if (arr_color.size() == 3) {
  1241.                             rend_set.color_palette_.push_back(svg::Color(svg::Rgb(red_,
  1242.                                                                                   green_,
  1243.                                                                                   blue_)));
  1244.                         }
  1245.                     }
  1246.                 }
  1247.             }            
  1248.         } catch(...) {
  1249.             std::cout << "unable to parsse init settings";
  1250.         }
  1251.        
  1252.     } else {
  1253.         std::cout << "render_settings is not map";
  1254.     }
  1255. }
  1256.    
  1257. void JSONReader::parse_node(const Node& root, TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request, map_renderer::RenderSettings& render_settings){
  1258.     Dict root_dictionary;
  1259.    
  1260.     if (root.is_dict()) {
  1261.         root_dictionary = root.as_dict();
  1262.        
  1263.         try {          
  1264.             parse_node_base(root_dictionary.at("base_requests"), catalogue);
  1265.         } catch(...) {
  1266.             std::cout << "base_requests is empty";
  1267.         }
  1268.        
  1269.         try {
  1270.             parse_node_stat(root_dictionary.at("stat_requests"), stat_request);
  1271.         } catch(...) {
  1272.             std::cout << "stat_requests is empty";
  1273.         }
  1274.        
  1275.         try {
  1276.             parse_node_render(root_dictionary.at("render_settings"), render_settings);
  1277.         } catch(...) {
  1278.             std::cout << "render_settings is empty";
  1279.         }
  1280.        
  1281.     } else {
  1282.         std::cout << "root is not map";
  1283.     }
  1284. }
  1285.    
  1286. void JSONReader::parse(TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request, map_renderer::RenderSettings& render_settings) {  
  1287.     parse_node(document_.get_root(),
  1288.                catalogue,
  1289.                stat_request,
  1290.                render_settings);
  1291. }
  1292.    
  1293. }//end namespace json
  1294. }//end namespace detail
  1295. }//end namespace transport_catalogue
  1296. -----------------------------------------------------------------------
  1297. json_reader.h
  1298. -----------------------------------------------------------------------
  1299. #pragma once
  1300. #include "json.h"
  1301. #include "transport_catalogue.h"
  1302. #include "map_renderer.h"
  1303.  
  1304. namespace transport_catalogue {
  1305. namespace detail {
  1306. namespace json {
  1307.    
  1308. class JSONReader{
  1309. public:
  1310.     JSONReader() = default;    
  1311.     JSONReader(Document doc);
  1312.     JSONReader(std::istream& input);
  1313.    
  1314.     void parse_node_base(const Node& root, TransportCatalogue& catalogue);
  1315.     void parse_node_stat(const Node& root, std::vector<StatRequest>& stat_request);
  1316.     void parse_node_render(const Node& node, map_renderer::RenderSettings& render_settings);
  1317.     void parse_node(const Node& root, TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request, map_renderer::RenderSettings& render_settings);
  1318.     void parse(TransportCatalogue& catalogue, std::vector<StatRequest>& stat_request, map_renderer::RenderSettings& render_settings);
  1319.    
  1320.     Stop parse_node_stop(Node& node);
  1321.     Bus parse_node_bus(Node& node, TransportCatalogue& catalogue);
  1322.     std::vector<Distance> parse_node_distances(Node& node, TransportCatalogue& catalogue);
  1323.    
  1324.     const Document& get_document() const;
  1325.    
  1326. private:
  1327.     Document document_;
  1328. };
  1329.    
  1330. }//end namespace json
  1331. }//end namespace detail
  1332. }//end namespace transport_catalogue
  1333. -----------------------------------------------------------------------
  1334. map_renderer.cpp
  1335. -----------------------------------------------------------------------
  1336. #include "map_renderer.h"
  1337.  
  1338. namespace map_renderer {
  1339.  
  1340. bool SphereProjector::is_zero(double value) {
  1341.     return std::abs(value) < EPSILON;
  1342. }
  1343.    
  1344. MapRenderer::MapRenderer(RenderSettings& render_settings) : render_settings_(render_settings) {}
  1345.  
  1346. svg::Point SphereProjector::operator()(geo::Coordinates coords) const {
  1347.     return {(coords.longitude - min_lon_) * zoom_coeff_ + padding_,
  1348.             (max_lat_ - coords.latitude) * zoom_coeff_ + padding_};
  1349. }
  1350.    
  1351. SphereProjector MapRenderer::get_sphere_projector(const std::vector<geo::Coordinates>& points) const {
  1352.         return SphereProjector(points.begin(),
  1353.                                points.end(),
  1354.                                render_settings_.width_,
  1355.                                render_settings_.height_,
  1356.                                render_settings_.padding_);
  1357. }
  1358.  
  1359. void MapRenderer::init_sphere_projector(std::vector<geo::Coordinates> points){
  1360.     sphere_projector = SphereProjector(points.begin(),
  1361.                                points.end(),
  1362.                                render_settings_.width_,
  1363.                                render_settings_.height_,
  1364.                                render_settings_.padding_);
  1365. }
  1366.    
  1367. RenderSettings MapRenderer::get_render_settings() const{
  1368.     return render_settings_;
  1369. }
  1370.  
  1371. int MapRenderer::get_palette_size() const{
  1372.     return render_settings_.color_palette_.size();
  1373. }
  1374.    
  1375. svg::Color MapRenderer::get_color(int line_number) const {
  1376.     return render_settings_.color_palette_[line_number];
  1377. }
  1378.  
  1379. void MapRenderer::set_line_properties(svg::Polyline& polyline,
  1380.                                       [[maybe_unused]] int line_number) const {
  1381.     using namespace std::literals;
  1382.    
  1383.     polyline.set_stroke_color(get_color(line_number));  
  1384.     polyline.set_fill_color("none"s);
  1385.     polyline.set_stroke_width(render_settings_.line_width_);
  1386.     polyline.set_stroke_linecap(svg::StrokeLineCap::ROUND);
  1387.     polyline.set_stroke_linejoin(svg::StrokeLineJoin::ROUND);  
  1388. }
  1389.    
  1390. void MapRenderer::set_route_text_common_properties(svg::Text& text,
  1391.                                                    const std::string& name,
  1392.                                                    svg::Point position) const {
  1393.     using namespace std::literals;
  1394.  
  1395.     text.set_position(position);
  1396.     text.set_offset({render_settings_.bus_label_offset_.first,
  1397.                      render_settings_.bus_label_offset_.second});
  1398.     text.set_font_size(render_settings_.bus_label_font_size_);
  1399.     text.set_font_family("Verdana");
  1400.     text.set_font_weight("bold");
  1401.     text.set_data(name);  
  1402. }
  1403.    
  1404. void MapRenderer::set_route_text_additional_properties(svg::Text& text,
  1405.                                                        const std::string& name,
  1406.                                                        svg::Point position) const {
  1407.     set_route_text_common_properties(text,
  1408.                                      name,
  1409.                                      position);
  1410.    
  1411.     text.set_fill_color(render_settings_.underlayer_color_);
  1412.     text.set_stroke_color(render_settings_.underlayer_color_);
  1413.     text.set_stroke_width(render_settings_.underlayer_width_);
  1414.     text.set_stroke_linejoin(svg::StrokeLineJoin::ROUND);
  1415.     text.set_stroke_linecap(svg::StrokeLineCap::ROUND);
  1416. }
  1417.  
  1418. void MapRenderer::set_route_text_color_properties(svg::Text& text,
  1419.                                                   const std::string& name,
  1420.                                                   int palette,
  1421.                                                   svg::Point position) const {
  1422.     set_route_text_common_properties(text,
  1423.                                      name,
  1424.                                      position);
  1425.    
  1426.     text.set_fill_color(get_color(palette));
  1427. }
  1428.    
  1429. void MapRenderer::set_stops_circles_properties(svg::Circle& circle,
  1430.                                                svg::Point position) const {
  1431.     using namespace std::literals;
  1432.    
  1433.     circle.set_center(position);
  1434.     circle.set_radius(render_settings_.stop_radius_);
  1435.     circle.set_fill_color("white");
  1436. }
  1437.    
  1438. void MapRenderer::set_stops_text_common_properties(svg::Text& text,
  1439.                                                    const std::string& name,
  1440.                                                    svg::Point position) const {
  1441.     using namespace std::literals;
  1442.  
  1443.     text.set_position(position);
  1444.     text.set_offset({render_settings_.stop_label_offset_.first,
  1445.                      render_settings_.stop_label_offset_.second});
  1446.     text.set_font_size(render_settings_.stop_label_font_size_);
  1447.     text.set_font_family("Verdana");
  1448.     text.set_data(name);
  1449. }
  1450.  
  1451. void MapRenderer::set_stops_text_additional_properties(svg::Text& text,
  1452.                                                        const std::string& name,
  1453.                                                        svg::Point position) const {
  1454.     using namespace std::literals;
  1455.     set_stops_text_common_properties(text,
  1456.                                      name,
  1457.                                      position);
  1458.  
  1459.     text.set_fill_color(render_settings_.underlayer_color_);
  1460.     text.set_stroke_color(render_settings_.underlayer_color_);
  1461.     text.set_stroke_width(render_settings_.underlayer_width_);
  1462.     text.set_stroke_linejoin(svg::StrokeLineJoin::ROUND);
  1463.     text.set_stroke_linecap(svg::StrokeLineCap::ROUND);
  1464. }
  1465.  
  1466. void MapRenderer::set_stops_text_color_properties(svg::Text& text,
  1467.                                                   const std::string& name,
  1468.                                                   svg::Point position) const {
  1469.     using namespace std::literals;
  1470.  
  1471.     set_stops_text_common_properties(text,
  1472.                                      name,
  1473.                                      position);
  1474.     text.set_fill_color("black");
  1475. }
  1476.    
  1477. void MapRenderer::add_line(std::vector<std::pair<Bus*, int>>& buses_palette) {    
  1478.     std::vector<geo::Coordinates> stops_geo_coords;
  1479.    
  1480.     for (auto [bus, palette] : buses_palette) {
  1481.        
  1482.         for (Stop* stop : bus->stops) {
  1483.             geo::Coordinates coordinates;
  1484.             coordinates.latitude = stop->latitude;
  1485.             coordinates.longitude = stop->longitude;
  1486.            
  1487.             stops_geo_coords.push_back(coordinates);
  1488.         }
  1489.        
  1490.         svg::Polyline bus_line;
  1491.         bool bus_empty = true;  
  1492.        
  1493.         for (auto& coord : stops_geo_coords) {
  1494.             bus_empty = false;
  1495.             bus_line.add_point(sphere_projector(coord));
  1496.         }
  1497.        
  1498.         if (!bus_empty) {
  1499.             set_line_properties(bus_line,
  1500.                                 palette);
  1501.             map_svg.add(bus_line);  
  1502.         }
  1503.        
  1504.         stops_geo_coords.clear();
  1505.     }
  1506. }
  1507.    
  1508. void MapRenderer::add_buses_name(std::vector<std::pair<Bus*, int>>& buses_palette){    
  1509.     std::vector<geo::Coordinates> stops_geo_coords;
  1510.     bool bus_empty = true;
  1511.    
  1512.     for (auto [bus, palette] : buses_palette) {  
  1513.        
  1514.         for (Stop* stop : bus->stops) {
  1515.             geo::Coordinates coordinates;
  1516.             coordinates.latitude = stop->latitude;
  1517.             coordinates.longitude = stop->longitude;
  1518.            
  1519.             stops_geo_coords.push_back(coordinates);
  1520.            
  1521.             if(bus_empty) bus_empty = false;
  1522.         }
  1523.        
  1524.         svg::Text route_name_roundtrip;
  1525.         svg::Text route_title_roundtrip;
  1526.         svg::Text route_name_notroundtrip;
  1527.         svg::Text route_title_notroundtrip;
  1528.        
  1529.         if (!bus_empty) {
  1530.            
  1531.             if (bus->is_roundtrip) {
  1532.                 set_route_text_additional_properties(route_name_roundtrip,
  1533.                                                      std::string(bus->name),
  1534.                                                      sphere_projector(stops_geo_coords[0]));
  1535.                 map_svg.add(route_name_roundtrip);
  1536.                
  1537.                 set_route_text_color_properties(route_title_roundtrip,
  1538.                                                 std::string(bus->name),
  1539.                                                 palette,
  1540.                                                 sphere_projector(stops_geo_coords[0]));
  1541.                 map_svg.add(route_title_roundtrip);
  1542.                
  1543.             } else {
  1544.                 set_route_text_additional_properties(route_name_roundtrip,
  1545.                                                      std::string(bus->name),
  1546.                                                      sphere_projector(stops_geo_coords[0]));
  1547.                 map_svg.add(route_name_roundtrip);
  1548.                
  1549.                 set_route_text_color_properties(route_title_roundtrip,
  1550.                                                 std::string(bus->name),
  1551.                                                 palette,
  1552.                                                 sphere_projector(stops_geo_coords[0]));
  1553.                 map_svg.add(route_title_roundtrip);
  1554.                
  1555.                 if (stops_geo_coords[0] != stops_geo_coords[stops_geo_coords.size()/2]) {
  1556.                     set_route_text_additional_properties(route_name_notroundtrip,
  1557.                                                          std::string(bus->name),
  1558.                                                          sphere_projector(stops_geo_coords[stops_geo_coords.size()/2]));
  1559.                     map_svg.add(route_name_notroundtrip);
  1560.                    
  1561.                     set_route_text_color_properties(route_title_notroundtrip,
  1562.                                                     std::string(bus->name),
  1563.                                                     palette,
  1564.                                                     sphere_projector(stops_geo_coords[stops_geo_coords.size()/2]));
  1565.                     map_svg.add(route_title_notroundtrip);
  1566.                 }
  1567.             }
  1568.         }
  1569.        
  1570.         bus_empty = false;
  1571.         stops_geo_coords.clear();
  1572.     }
  1573. }
  1574.    
  1575. void MapRenderer::add_stops_circle(std::vector<Stop*>& stops){
  1576.     std::vector<geo::Coordinates> stops_geo_coords;      
  1577.     svg::Circle icon;
  1578.    
  1579.     for (Stop* stop_info : stops) {
  1580.        
  1581.         if (stop_info) {
  1582.             geo::Coordinates coordinates;
  1583.             coordinates.latitude = stop_info->latitude;
  1584.             coordinates.longitude = stop_info->longitude;
  1585.  
  1586.             set_stops_circles_properties(icon,
  1587.                                          sphere_projector(coordinates));
  1588.             map_svg.add(icon);  
  1589.         }
  1590.     }
  1591. }
  1592.  
  1593. void MapRenderer::add_stops_name(std::vector<Stop*>& stops){    
  1594.     std::vector<geo::Coordinates> stops_geo_coords;    
  1595.    
  1596.     svg::Text svg_stop_name;
  1597.     svg::Text svg_stop_name_title;
  1598.    
  1599.     for (Stop* stop_info : stops) {
  1600.        
  1601.         if (stop_info) {
  1602.             geo::Coordinates coordinates;
  1603.             coordinates.latitude = stop_info->latitude;
  1604.             coordinates.longitude = stop_info->longitude;            
  1605.            
  1606.             set_stops_text_additional_properties(svg_stop_name,
  1607.                                                  stop_info->name,
  1608.                                                  sphere_projector(coordinates));
  1609.             map_svg.add(svg_stop_name);
  1610.            
  1611.             set_stops_text_color_properties(svg_stop_name_title,
  1612.                                             stop_info->name,
  1613.                                             sphere_projector(coordinates));
  1614.             map_svg.add(svg_stop_name_title);
  1615.         }
  1616.     }
  1617. }
  1618.  
  1619. void MapRenderer::get_stream_map(std::ostream& stream_) {
  1620.     map_svg.render(stream_);
  1621. }
  1622.    
  1623. }//end namespace map_renderer
  1624. -----------------------------------------------------------------------
  1625. map_renderer.h
  1626. -----------------------------------------------------------------------
  1627. #pragma once
  1628. #include <iostream>
  1629. #include <optional>
  1630. #include <algorithm>
  1631. #include <cstdlib>
  1632.  
  1633. #include "domain.h"
  1634. #include "geo.h"
  1635. #include "svg.h"
  1636.  
  1637. using namespace domain;
  1638.  
  1639. namespace map_renderer {
  1640.    
  1641. inline const double EPSILON = 1e-6;
  1642.  
  1643. class SphereProjector {
  1644. public:
  1645.     SphereProjector() = default;
  1646.    
  1647.     template <typename InputIt>
  1648.     SphereProjector(InputIt points_begin,
  1649.                     InputIt points_end,
  1650.                     double max_width,
  1651.                     double max_height,
  1652.                     double padding);
  1653.  
  1654.     svg::Point operator()(geo::Coordinates coords) const;
  1655.  
  1656. private:
  1657.     double padding_;
  1658.     double min_lon_ = 0;
  1659.     double max_lat_ = 0;
  1660.     double zoom_coeff_ = 0;
  1661.    
  1662.     bool is_zero(double value);
  1663. };
  1664.    
  1665. struct RenderSettings {
  1666.     double width_;
  1667.     double height_;
  1668.     double padding_;
  1669.     double line_width_;
  1670.     double stop_radius_;
  1671.     int bus_label_font_size_;
  1672.     std::pair<double, double> bus_label_offset_;
  1673.     int stop_label_font_size_;
  1674.     std::pair<double, double> stop_label_offset_;
  1675.     svg::Color underlayer_color_;
  1676.     double underlayer_width_;
  1677.     std::vector<svg::Color> color_palette_;
  1678. };
  1679.    
  1680. class MapRenderer {
  1681.  
  1682. public:
  1683.     MapRenderer(RenderSettings& render_settings);  
  1684.    
  1685.     SphereProjector get_sphere_projector(const std::vector<geo::Coordinates>& points) const;
  1686.     void init_sphere_projector(std::vector<geo::Coordinates> points);
  1687.    
  1688.     RenderSettings get_render_settings() const;
  1689.     int get_palette_size() const;
  1690.     svg::Color get_color(int line_number) const;
  1691.        
  1692.     void set_line_properties(svg::Polyline& polyline, int line_number) const;
  1693.    
  1694.     void set_route_text_common_properties(svg::Text &text, const std::string& name, svg::Point position) const;
  1695.     void set_route_text_additional_properties(svg::Text& text, const std::string& name, svg::Point position) const;
  1696.     void set_route_text_color_properties(svg::Text& text, const std::string& name, int palette, svg::Point position) const;
  1697.    
  1698.     void set_stops_circles_properties(svg::Circle& circle, svg::Point position) const;
  1699.    
  1700.     void set_stops_text_common_properties(svg::Text& text, const std::string& name, svg::Point position) const;
  1701.     void set_stops_text_additional_properties(svg::Text& text, const std::string& name, svg::Point position) const;
  1702.     void set_stops_text_color_properties(svg::Text& text, const std::string& name, svg::Point position) const;
  1703.    
  1704.     void add_line(std::vector<std::pair<Bus*, int>>& buses_palette);
  1705.     void add_buses_name(std::vector<std::pair<Bus*, int>>& buses_palette);
  1706.     void add_stops_circle(std::vector<Stop*>& stops_name);
  1707.     void add_stops_name(std::vector<Stop*>& stops_name);    
  1708.    
  1709.     void get_stream_map(std::ostream& stream_);
  1710.    
  1711. private:
  1712.     SphereProjector sphere_projector;
  1713.     RenderSettings& render_settings_;
  1714.     svg::Document map_svg;
  1715. };
  1716.  
  1717. template <typename InputIt>
  1718.     SphereProjector::SphereProjector(InputIt points_begin,
  1719.                                      InputIt points_end,
  1720.                                      double max_width,
  1721.                                      double max_height,
  1722.                                      double padding) : padding_(padding) {
  1723.         if (points_begin == points_end) {
  1724.             return;
  1725.         }
  1726.  
  1727.         const auto [left_it,
  1728.                     right_it] = std::minmax_element(points_begin,
  1729.                                                     points_end,
  1730.             [](auto lhs, auto rhs) {
  1731.                 return lhs.longitude < rhs.longitude;
  1732.             });
  1733.        
  1734.         min_lon_ = left_it->longitude;
  1735.         const double max_lon = right_it->longitude;
  1736.  
  1737.         const auto [bottom_it,
  1738.                     top_it] = std::minmax_element(points_begin,
  1739.                                                   points_end,
  1740.             [](auto lhs, auto rhs) {
  1741.                 return lhs.latitude < rhs.latitude;
  1742.             });
  1743.        
  1744.         const double min_lat = bottom_it->latitude;
  1745.         max_lat_ = top_it->latitude;
  1746.  
  1747.         std::optional<double> width_zoom;
  1748.         if (!is_zero(max_lon - min_lon_)) {
  1749.             width_zoom = (max_width - 2 * padding)
  1750.                          / (max_lon - min_lon_);
  1751.         }
  1752.  
  1753.         std::optional<double> height_zoom;
  1754.         if (!is_zero(max_lat_ - min_lat)) {
  1755.             height_zoom = (max_height - 2 * padding)
  1756.                           / (max_lat_ - min_lat);
  1757.         }
  1758.  
  1759.         if (width_zoom && height_zoom) {
  1760.             zoom_coeff_ = std::min(*width_zoom,
  1761.                                    *height_zoom);    
  1762.         } else if (width_zoom) {
  1763.             zoom_coeff_ = *width_zoom;
  1764.            
  1765.         } else if (height_zoom) {
  1766.             zoom_coeff_ = *height_zoom;
  1767.            
  1768.         }
  1769.     }
  1770.    
  1771. }//end namespace map_renderer
  1772. -----------------------------------------------------------------------
  1773. request_handler.cpp
  1774. -----------------------------------------------------------------------
  1775. #include "request_handler.h"
  1776.  
  1777. namespace request_handler {
  1778.    
  1779. Node RequestHandler::execute_make_node_stop(int id_request, const StopQueryResult& stop_info){
  1780.     Node result;
  1781.     Array buses;
  1782.     Builder builder;
  1783.  
  1784.     std::string str_not_found = "not found";
  1785.  
  1786.     if (stop_info.not_found) {
  1787.         builder.start_dict()
  1788.                .key("request_id").value(id_request)
  1789.                .key("error_message").value(str_not_found)
  1790.                .end_dict();
  1791.        
  1792.         result = builder.build();
  1793.        
  1794.     } else {
  1795.         builder.start_dict()
  1796.                .key("request_id").value(id_request)
  1797.                .key("buses").start_array();
  1798.  
  1799.         for (std::string bus_name : stop_info.buses_name) {
  1800.             builder.value(bus_name);
  1801.         }
  1802.  
  1803.         builder.end_array().end_dict();
  1804.        
  1805.         result = builder.build();
  1806.     }
  1807.  
  1808.     return result;
  1809. }
  1810.  
  1811. Node RequestHandler::execute_make_node_bus(int id_request, const BusQueryResult& bus_info){
  1812.     Node result;
  1813.     std::string str_not_found = "not found";
  1814.  
  1815.     if (bus_info.not_found) {
  1816.         result = Builder{}.start_dict()
  1817.                           .key("request_id").value(id_request)
  1818.                           .key("error_message").value(str_not_found)
  1819.                           .end_dict()
  1820.                           .build();
  1821.     } else {
  1822.         result = Builder{}.start_dict()
  1823.                           .key("request_id").value(id_request)
  1824.                           .key("curvature").value(bus_info.curvature)
  1825.                           .key("route_length").value(bus_info.route_length)
  1826.                           .key("stop_count").value(bus_info.stops_on_route)
  1827.                           .key("unique_stop_count").value(bus_info.unique_stops)
  1828.                           .end_dict()
  1829.                           .build();
  1830.     }
  1831.  
  1832.     return result;
  1833. }    
  1834.      
  1835. Node RequestHandler::execute_make_node_map(int id_request, TransportCatalogue& catalogue_, RenderSettings render_settings){
  1836.     Node result;
  1837.  
  1838.     std::ostringstream map_stream;
  1839.     std::string map_str;
  1840.  
  1841.     MapRenderer map_catalogue(render_settings);
  1842.    
  1843.     map_catalogue.init_sphere_projector(get_stops_coordinates(catalogue_));
  1844.    
  1845.     execute_render_map(map_catalogue, catalogue_);
  1846.     map_catalogue.get_stream_map(map_stream);
  1847.     map_str = map_stream.str();
  1848.  
  1849.     result = Builder{}.start_dict()
  1850.                       .key("request_id").value(id_request)
  1851.                       .key("map").value(map_str)
  1852.                       .end_dict()
  1853.                       .build();
  1854.  
  1855.     return result;
  1856. }
  1857.    
  1858. void RequestHandler::execute_queries(TransportCatalogue& catalogue,
  1859.                                      std::vector<StatRequest>& stat_requests,
  1860.                                      RenderSettings& render_settings) {
  1861.     std::vector<Node> result_request;
  1862.     for (StatRequest req : stat_requests) {
  1863.  
  1864.         if (req.type == "Stop") {
  1865.             result_request.push_back(execute_make_node_stop(req.id, stop_query(catalogue, req.name)));
  1866.            
  1867.         } else if (req.type == "Bus") {
  1868.             result_request.push_back(execute_make_node_bus(req.id, bus_query(catalogue, req.name)));
  1869.            
  1870.         } else if (req.type == "Map") {
  1871.             result_request.push_back(execute_make_node_map(req.id, catalogue, render_settings));
  1872.         }
  1873.     }
  1874.  
  1875.     doc_out = Document{Node(result_request)};
  1876. }
  1877.  
  1878. void RequestHandler::execute_render_map(MapRenderer& map_catalogue, TransportCatalogue& catalogue) const {  
  1879.     std::vector<std::pair<Bus*, int>> buses_palette;  
  1880.     std::vector<Stop*> stops_sort;
  1881.     int palette_size = 0;
  1882.     int palette_index = 0;
  1883.    
  1884.     palette_size = map_catalogue.get_palette_size();
  1885.     if (palette_size == 0) {
  1886.         std::cout << "color palette is empty";
  1887.         return;
  1888.     }
  1889.  
  1890.     auto buses = catalogue.get_busname_to_bus();  
  1891.     if (buses.size() > 0) {
  1892.        
  1893.         for (std::string_view bus_name : get_sort_buses_names(catalogue)) {
  1894.             Bus* bus_info = catalogue.get_bus(bus_name);
  1895.  
  1896.             if (bus_info) {  
  1897.                 if (bus_info->stops.size() > 0) {
  1898.                     buses_palette.push_back(std::make_pair(bus_info, palette_index));
  1899.                     palette_index++;
  1900.                    
  1901.                     if (palette_index == palette_size) {
  1902.                         palette_index = 0;
  1903.                     }
  1904.                 }
  1905.             }
  1906.         }
  1907.  
  1908.         if (buses_palette.size() > 0) {
  1909.             map_catalogue.add_line(buses_palette);
  1910.             map_catalogue.add_buses_name(buses_palette);            
  1911.         }          
  1912.     }
  1913.  
  1914.     auto stops = catalogue.get_stopname_to_stop();  
  1915.     if (stops.size() > 0) {
  1916.         std::vector<std::string_view> stops_name;
  1917.  
  1918.         for (auto& [stop_name, stop] : stops) {
  1919.            
  1920.             if (stop->buses.size() > 0) {
  1921.                 stops_name.push_back(stop_name);
  1922.             }
  1923.         }
  1924.        
  1925.         std::sort(stops_name.begin(), stops_name.end());
  1926.        
  1927.         for(std::string_view stop_name : stops_name){
  1928.             Stop* stop = catalogue.get_stop(stop_name);
  1929.             if(stop){
  1930.                 stops_sort.push_back(stop);
  1931.             }
  1932.         }
  1933.        
  1934.         if (stops_sort.size() > 0) {
  1935.             map_catalogue.add_stops_circle(stops_sort);
  1936.             map_catalogue.add_stops_name(stops_sort);
  1937.         }
  1938.     }
  1939. }
  1940.    
  1941. std::vector<geo::Coordinates> RequestHandler::get_stops_coordinates(TransportCatalogue& catalogue_) const {
  1942.    
  1943.     std::vector<geo::Coordinates> stops_coordinates;
  1944.     auto buses = catalogue_.get_busname_to_bus();
  1945.    
  1946.     for (auto& [busname, bus] : buses) {
  1947.         for (auto& stop : bus->stops) {
  1948.             geo::Coordinates coordinates;
  1949.             coordinates.latitude = stop->latitude;
  1950.             coordinates.longitude = stop->longitude;
  1951.            
  1952.             stops_coordinates.push_back(coordinates);
  1953.         }
  1954.     }
  1955.     return stops_coordinates;
  1956. }
  1957.    
  1958. std::vector<std::string_view> RequestHandler::get_sort_buses_names(TransportCatalogue& catalogue_) const {
  1959.     std::vector<std::string_view> buses_names;
  1960.    
  1961.     auto buses = catalogue_.get_busname_to_bus();
  1962.     if (buses.size() > 0) {
  1963.        
  1964.         for (auto& [busname, bus] : buses) {
  1965.             buses_names.push_back(busname);
  1966.         }  
  1967.  
  1968.         std::sort(buses_names.begin(), buses_names.end());
  1969.        
  1970.         return buses_names;
  1971.        
  1972.     } else {
  1973.         return {};
  1974.     }
  1975. }
  1976.  
  1977. BusQueryResult RequestHandler::bus_query(TransportCatalogue& catalogue, std::string_view bus_name) {
  1978.     BusQueryResult bus_info;
  1979.     Bus* bus = catalogue.get_bus(bus_name);
  1980.    
  1981.     if (bus != nullptr) {                
  1982.         bus_info.name = bus->name;
  1983.         bus_info.not_found = false;
  1984.         bus_info.stops_on_route = bus->stops.size();
  1985.         bus_info.unique_stops = catalogue.get_uniq_stops(bus).size();
  1986.         bus_info.route_length = bus->route_length;
  1987.         bus_info.curvature = double(catalogue.get_distance_to_bus(bus)
  1988.                                     /catalogue.get_length(bus));                    
  1989.     } else {  
  1990.         bus_info.name = bus_name;
  1991.         bus_info.not_found = true;
  1992.     }
  1993.    
  1994.     return bus_info;
  1995. }  
  1996.    
  1997. StopQueryResult RequestHandler::stop_query(TransportCatalogue& catalogue, std::string_view stop_name) {
  1998.     std::unordered_set<const Bus*> unique_buses;
  1999.     StopQueryResult stop_info;
  2000.     Stop* stop = catalogue.get_stop(stop_name);
  2001.  
  2002.     if (stop != NULL) {
  2003.        
  2004.         stop_info.name = stop->name;
  2005.         stop_info.not_found = false;
  2006.         unique_buses = catalogue.stop_get_uniq_buses(stop);
  2007.        
  2008.         if (unique_buses.size() > 0){
  2009.             for (const Bus* bus : unique_buses) {
  2010.                 stop_info.buses_name.push_back(bus->name);
  2011.             }
  2012.            
  2013.             std::sort(stop_info.buses_name.begin(), stop_info.buses_name.end());
  2014.         }  
  2015.        
  2016.     } else {    
  2017.         stop_info.name = stop_name;
  2018.         stop_info.not_found = true;
  2019.     }
  2020.    
  2021.     return stop_info;
  2022. }
  2023.    
  2024. const Document& RequestHandler::get_document() {return doc_out;}
  2025.    
  2026. }//end namespace request_handler
  2027. -----------------------------------------------------------------------
  2028. request_handler.h
  2029. -----------------------------------------------------------------------
  2030. #pragma once
  2031.  
  2032. #include "transport_catalogue.h"
  2033. #include "map_renderer.h"
  2034. #include "json_builder.h"
  2035.  
  2036. using namespace transport_catalogue;
  2037. using namespace map_renderer;
  2038. using namespace transport_catalogue::detail::json;
  2039. using namespace transport_catalogue::detail::json::builder;
  2040.  
  2041. namespace request_handler {
  2042.  
  2043. class RequestHandler {
  2044. public:
  2045.            
  2046.     RequestHandler() = default;
  2047.    
  2048.     std::vector<geo::Coordinates> get_stops_coordinates(TransportCatalogue& catalogue_) const;
  2049.     std::vector<std::string_view> get_sort_buses_names(TransportCatalogue& catalogue_) const;
  2050.    
  2051.     BusQueryResult bus_query(TransportCatalogue& catalogue, std::string_view str);
  2052.     StopQueryResult stop_query(TransportCatalogue& catalogue, std::string_view stop_name);
  2053.    
  2054.     Node execute_make_node_stop(int id_request, const StopQueryResult& query_result);
  2055.     Node execute_make_node_bus(int id_request, const BusQueryResult& query_result);
  2056.     Node execute_make_node_map(int id_request, TransportCatalogue& catalogue, RenderSettings render_settings);
  2057.     void execute_queries(TransportCatalogue& catalogue, std::vector<StatRequest>& stat_requests, RenderSettings& render_settings);
  2058.     void execute_render_map(MapRenderer& map_catalogue, TransportCatalogue& catalogue_) const;
  2059.        
  2060.     const Document& get_document();
  2061.  
  2062. private:
  2063.     Document doc_out;
  2064. };
  2065.    
  2066. }//end namespace request_handler
  2067. -----------------------------------------------------------------------
  2068. svg.cpp
  2069. -----------------------------------------------------------------------
  2070. #include "svg.h"
  2071.  
  2072. namespace svg {
  2073.  
  2074. using namespace std::literals;
  2075.  
  2076. Rgb::Rgb(uint8_t red, uint8_t green, uint8_t blue) : red_(red)
  2077.                                                    , green_(green)
  2078.                                                    , blue_(blue) {}  
  2079.    
  2080. Rgba::Rgba(uint8_t red, uint8_t green, uint8_t blue, double opacity) : red_(red)
  2081.                                                                      , green_(green)
  2082.                                                                      , blue_(blue)
  2083.                                                                      , opacity_(opacity) {}
  2084.    
  2085. inline void print_color(std::ostream& out, Rgb& rgb) {
  2086.     out << "rgb("sv << static_cast<short>(rgb.red_) << ","sv
  2087.                     << static_cast<short>(rgb.green_) << ","sv
  2088.                     << static_cast<short>(rgb.blue_) << ")"sv;
  2089. }
  2090.    
  2091. inline void print_color(std::ostream& out, Rgba& rgba) {
  2092.     out << "rgba("sv << static_cast<short>(rgba.red_) << ","sv
  2093.                      << static_cast<short>(rgba.green_) << ","sv
  2094.                      << static_cast<short>(rgba.blue_) << ","sv
  2095.                      << (rgba.opacity_) << ")"sv;
  2096. }
  2097.    
  2098. inline void print_color(std::ostream& out, std::monostate) {
  2099.     out << "none"sv;
  2100. }
  2101.  
  2102. inline void print_color(std::ostream& out, std::string& color) {
  2103.     out << color;
  2104. }
  2105.    
  2106. std::ostream& operator<<(std::ostream& out, const Color& color) {
  2107.     std::visit([&out](auto value) {
  2108.             print_color(out, value);
  2109.     }, color);
  2110.    
  2111.     return out;
  2112. }
  2113.    
  2114. RenderContext::RenderContext(std::ostream& out) : out_(out) {}
  2115.    
  2116. RenderContext RenderContext::indented() const {
  2117.         return {out_,
  2118.                 indent_step_,
  2119.                 indent_ + indent_step_};
  2120. }
  2121.    
  2122. void RenderContext::render_indent() const {
  2123.         for (int i = 0; i < indent_; ++i) {
  2124.             out_.put(' ');
  2125.         }
  2126. }
  2127.  
  2128. void Object::render(const RenderContext& context) const {
  2129.     context.render_indent();
  2130.     render_object(context);
  2131.     context.out_ << std::endl;
  2132. }
  2133.  
  2134. Circle& Circle::set_center(Point center)  {
  2135.     center_ = center;
  2136.     return *this;
  2137. }
  2138.  
  2139. Circle& Circle::set_radius(double radius)  {
  2140.     radius_ = radius;
  2141.     return *this;
  2142. }
  2143.  
  2144. void Circle::render_object(const RenderContext& context) const {
  2145.     std::ostream& out = context.out_;
  2146.  
  2147.     out << "<circle cx=\""sv << center_.x
  2148.         << "\" cy=\""sv << center_.y << "\" "sv;
  2149.     out << "r=\""sv << radius_ << "\" "sv;
  2150.    
  2151.     render_attrs(context.out_);
  2152.     out << "/>"sv;
  2153. }
  2154.    
  2155. Polyline& Polyline::add_point(Point point) {
  2156.     points_.emplace_back(point);
  2157.     return *this;
  2158. }
  2159.  
  2160. void Polyline::render_object(const RenderContext& context) const {
  2161.    
  2162.     std::ostream& out = context.out_;
  2163.     out << "<polyline points=\"";
  2164.    
  2165.     for (size_t i = 0; i < points_.size(); ++i) {
  2166.         out << points_[i].x << ","sv << points_[i].y;
  2167.  
  2168.         if (i+1 != points_.size()) {
  2169.             out << " "sv;
  2170.         }
  2171.     }
  2172.     out << "\" ";
  2173.     render_attrs(context.out_);
  2174.     out << "/>";
  2175. }
  2176.    
  2177. Text& Text::set_position(Point pos) {
  2178.     position_ = pos;
  2179.     return *this;
  2180. }
  2181.  
  2182. Text& Text::set_offset(Point offset) {
  2183.     offset_ = offset;
  2184.     return *this;
  2185. }
  2186.    
  2187. Text& Text::set_font_size(uint32_t size) {
  2188.     font_size_ = size;
  2189.     return *this;
  2190. }
  2191.  
  2192. Text& Text::set_font_family(std::string font_family) {
  2193.     font_family_ = std::move(font_family);
  2194.     return *this;
  2195. }
  2196.  
  2197. Text& Text::set_font_weight(std::string font_weight) {
  2198.     font_weight_ = std::move(font_weight);
  2199.     return *this;
  2200. }
  2201.  
  2202. Text& Text::set_data(std::string data) {
  2203.     data_ = std::move(data);
  2204.     return *this;
  2205. }
  2206.  
  2207. std::string Text::delete_spaces(const std::string& str) {
  2208.     if (str.empty()) {
  2209.         return {};
  2210.     } else {
  2211.        
  2212.         auto left = str.find_first_not_of(' ');
  2213.         auto right = str.find_last_not_of(' ');
  2214.         return str.substr(left, right - left + 1);  
  2215.     }
  2216. }
  2217.  
  2218. std::string Text::uniq_symbols(const std::string& str) {
  2219.    
  2220.     std::string out;
  2221.  
  2222.     for (char ch : str) {
  2223.        
  2224.         if (ch == '"') {
  2225.             out += "&quot;"sv;
  2226.             continue;
  2227.            
  2228.         } else if (ch == '`' || ch == '\'') {
  2229.             out += "&apos;"sv;
  2230.             continue;
  2231.            
  2232.         } else if (ch == '<') {
  2233.             out += "&lt;"sv;
  2234.             continue;
  2235.            
  2236.         } else if (ch == '>') {
  2237.             out += "&gt;"sv;
  2238.             continue;
  2239.            
  2240.         } else if (ch == '&') {
  2241.             out += "&amp;"sv;
  2242.             continue;
  2243.            
  2244.         } else {
  2245.            
  2246.         }
  2247.        
  2248.         out += ch;
  2249.     }
  2250.  
  2251.     return out;
  2252. }
  2253.  
  2254. void Text::render_object(const RenderContext& context) const {
  2255.    
  2256.     std::ostream& out = context.out_;
  2257.     out << "<text ";
  2258.     render_attrs(context.out_);
  2259.     out << "x=\""
  2260.         << position_.x << "\" y=\""
  2261.         << position_.y << "\" "
  2262.         << "dx=\""
  2263.         << offset_.x << "\" dy=\""
  2264.         << offset_.y << "\" "
  2265.         << "font-size=\""
  2266.         << font_size_ << "\" ";
  2267.  
  2268.     if (!font_family_.empty()) {
  2269.         out << "font-family=\"" << font_family_ << "\" ";
  2270.     }
  2271.  
  2272.     if (!font_weight_.empty()) {
  2273.         out << "font-weight=\"" << font_weight_ << "\"";
  2274.     }
  2275.  
  2276.     out << ">"sv << delete_spaces(uniq_symbols(data_)) << "</text>"sv;
  2277.  
  2278. }
  2279.  
  2280. void Document::render(std::ostream& out) const{
  2281.     int indent = 2;
  2282.     int indent_step = 2;
  2283.  
  2284.     RenderContext context(out, indent_step, indent);
  2285.  
  2286.     const std::string_view xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"sv;
  2287.     const std::string_view svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"sv;
  2288.  
  2289.     out << xml << "\n"sv << svg << "\n"sv;
  2290.  
  2291.     for (const auto& object : objects_) {
  2292.         object->render(context);
  2293.     }
  2294.    
  2295.     out << "</svg>"sv;
  2296. }
  2297.  
  2298. }//end namespace svg
  2299. -----------------------------------------------------------------------
  2300. svg.h
  2301. -----------------------------------------------------------------------
  2302. #pragma once
  2303. #define _USE_MATH_DEFINES
  2304.  
  2305. #include <cstdint>
  2306. #include <iostream>
  2307. #include <memory>
  2308. #include <string>
  2309. #include <vector>
  2310. #include <optional>
  2311. #include <cmath>
  2312. #include <variant>
  2313.  
  2314. namespace svg {
  2315.  
  2316. class Rgb {
  2317. public:
  2318.     Rgb() = default;
  2319.     Rgb(uint8_t red, uint8_t green, uint8_t blue);
  2320.    
  2321.     uint8_t red_ = 0;
  2322.     uint8_t green_ = 0;
  2323.     uint8_t blue_ = 0;
  2324. };
  2325. inline void print_color(std::ostream& out, Rgb& rgb);
  2326.  
  2327. class Rgba {
  2328. public:
  2329.     Rgba() = default;
  2330.     Rgba(uint8_t red, uint8_t green, uint8_t blue, double opacity);
  2331.    
  2332.     uint8_t red_ = 0;
  2333.     uint8_t green_ = 0;
  2334.     uint8_t blue_ = 0;
  2335.     double opacity_ = 1.0;
  2336. };  
  2337. inline void print_color(std::ostream& out, Rgba& rgba);
  2338.  
  2339. using Color = std::variant<std::monostate, std::string, Rgb, Rgba>;
  2340. inline const Color NoneColor{"none"};  
  2341.    
  2342. inline void print_color(std::ostream& out, std::monostate);
  2343. inline void print_color(std::ostream& out, std::string& color);
  2344. std::ostream& operator<<(std::ostream& out, const Color& color);
  2345.    
  2346. enum class StrokeLineCap {
  2347.     BUTT,
  2348.     ROUND,
  2349.     SQUARE,
  2350. };
  2351.    
  2352. inline std::ostream &operator<<(std::ostream &out, StrokeLineCap stroke_line_cap) {
  2353.     using namespace std::literals;
  2354.    
  2355.     if (stroke_line_cap == StrokeLineCap::BUTT) {
  2356.         out << "butt"sv;
  2357.     } else if (stroke_line_cap == StrokeLineCap::ROUND) {
  2358.         out << "round"sv;
  2359.     } else if (stroke_line_cap == StrokeLineCap::SQUARE) {
  2360.         out << "square"sv;
  2361.     }
  2362.     return out;
  2363. }
  2364.  
  2365. enum class StrokeLineJoin {
  2366.     ARCS,
  2367.     BEVEL,
  2368.     MITER,
  2369.     MITER_CLIP,
  2370.     ROUND,
  2371. };
  2372.    
  2373. inline std::ostream &operator<<(std::ostream &out, StrokeLineJoin stroke_line_join) {
  2374.     using namespace std::literals;
  2375.    
  2376.     if (stroke_line_join == StrokeLineJoin::ARCS) {
  2377.         out << "arcs"sv;
  2378.     } else if (stroke_line_join == StrokeLineJoin::BEVEL) {
  2379.         out << "bevel"sv;
  2380.     } else if (stroke_line_join == StrokeLineJoin::MITER) {
  2381.         out << "miter"sv;
  2382.     } else if (stroke_line_join == StrokeLineJoin::MITER_CLIP) {
  2383.         out << "miter-clip"sv;
  2384.     } else if (stroke_line_join == StrokeLineJoin::ROUND) {
  2385.         out << "round"sv;
  2386.     }
  2387.     return out;
  2388. }
  2389.    
  2390. template<typename Owner>
  2391. class PathProps {
  2392. public:
  2393.     Owner& set_fill_color(const Color& color) {
  2394.         fill_color_ = std::move(color);
  2395.         return as_owner();
  2396.     }
  2397.  
  2398.     Owner& set_stroke_color(const Color& color) {
  2399.         stroke_color_ = std::move(color);
  2400.         return as_owner();
  2401.     }
  2402.  
  2403.     Owner& set_stroke_width(double width) {
  2404.         stroke_width_ = width;
  2405.         return as_owner();
  2406.     }
  2407.  
  2408.     Owner& set_stroke_linecap(StrokeLineCap line_cap) {
  2409.         stroke_line_cap_ = line_cap;
  2410.         return as_owner();
  2411.     }
  2412.  
  2413.     Owner& set_stroke_linejoin(StrokeLineJoin line_join) {
  2414.         stroke_line_join_ = line_join;
  2415.         return as_owner();
  2416.     }
  2417.  
  2418. protected:
  2419.     ~PathProps() = default;
  2420.  
  2421.     void render_attrs(std::ostream &out) const {
  2422.         using namespace std::literals;
  2423.  
  2424.         if (fill_color_ != std::nullopt) {
  2425.             out << "fill=\""sv << *fill_color_ << "\" "sv;
  2426.         }
  2427.         if (stroke_color_ != std::nullopt) {
  2428.             out << "stroke=\""sv << *stroke_color_ << "\" "sv;
  2429.         }
  2430.         if (stroke_width_ != std::nullopt) {
  2431.             out << "stroke-width=\""sv << *stroke_width_ << "\" "sv;
  2432.         }
  2433.         if (stroke_line_cap_ != std::nullopt) {
  2434.             out << "stroke-linecap=\""sv << *stroke_line_cap_ << "\" "sv;
  2435.         }
  2436.         if (stroke_line_join_ != std::nullopt) {
  2437.             out << "stroke-linejoin=\""sv << *stroke_line_join_ << "\" "sv;
  2438.         }
  2439.     }
  2440.    
  2441. private:
  2442.     std::optional<Color> fill_color_;
  2443.     std::optional<Color> stroke_color_;
  2444.     std::optional<double> stroke_width_;
  2445.     std::optional<StrokeLineCap> stroke_line_cap_;
  2446.     std::optional<StrokeLineJoin> stroke_line_join_;
  2447.    
  2448.     Owner& as_owner() {
  2449.         return static_cast<Owner&>(*this);
  2450.     }
  2451. };
  2452.    
  2453. struct Point {
  2454.     Point() = default;
  2455.     Point(double x, double y) : x(x)
  2456.                               , y(y) {}
  2457.     double x = 0;
  2458.     double y = 0;
  2459. };
  2460.  
  2461. struct RenderContext {
  2462.     RenderContext(std::ostream& out);
  2463.     RenderContext(std::ostream& out, int indent_step, int indent = 0) : out_(out)
  2464.                                                                       , indent_step_(indent_step)
  2465.                                                                       , indent_(indent) {}
  2466.     RenderContext indented() const;
  2467.     void render_indent() const;
  2468.  
  2469.     std::ostream& out_;
  2470.     int indent_step_ = 0;
  2471.     int indent_ = 0;
  2472. };
  2473.  
  2474. class Object {
  2475. public:
  2476.     void render(const RenderContext& context) const;
  2477.     virtual ~Object() = default;
  2478.  
  2479. private:
  2480.     virtual void render_object(const RenderContext& context) const = 0;
  2481. };
  2482.  
  2483. class Circle final : public Object, public PathProps<Circle> {
  2484. public:
  2485.     Circle& set_center(Point center);
  2486.     Circle& set_radius(double radius);
  2487.  
  2488. private:
  2489.     Point center_;
  2490.     double radius_ = 1.0;
  2491.    
  2492.     void render_object(const RenderContext& context) const override;
  2493. };
  2494.  
  2495. class Polyline final : public Object, public PathProps<Polyline> {
  2496. public:
  2497.     Polyline& add_point(Point point);
  2498.    
  2499. private:
  2500.     std::vector<Point> points_;
  2501.     void render_object(const RenderContext& context) const override;
  2502. };
  2503.  
  2504. class Text final : public Object, public PathProps<Text> {
  2505. public:
  2506.     Text& set_position(Point pos);
  2507.     Text& set_offset(Point offset);
  2508.     Text& set_font_size(uint32_t size);
  2509.     Text& set_font_family(std::string font_family);
  2510.     Text& set_font_weight(std::string font_weight);
  2511.     Text& set_data(std::string data);
  2512.  
  2513. private:
  2514.     Point position_;
  2515.     Point offset_;
  2516.     std::string font_family_;
  2517.     std::string font_weight_;
  2518.     uint32_t font_size_ = 1;
  2519.     std::string data_;
  2520.      
  2521.     static std::string delete_spaces(const std::string& str);
  2522.     static std::string uniq_symbols(const std::string& str);
  2523.    
  2524.     void render_object(const RenderContext& context) const override;
  2525. };
  2526.  
  2527. class ObjectContainer {
  2528. public:
  2529.     virtual ~ObjectContainer() = default;
  2530.  
  2531.     template<typename Obj>
  2532.     void add(Obj obj);
  2533.  
  2534.     virtual void add_ptr(std::unique_ptr<Object> &&) = 0;
  2535.  
  2536. protected:
  2537.     std::vector<std::unique_ptr<Object>> objects_;
  2538. };
  2539.    
  2540. template<typename Obj>
  2541. void ObjectContainer::add(Obj obj) {
  2542.     objects_.emplace_back(std::make_unique<Obj>(std::move(obj)));
  2543. }
  2544.    
  2545. class Drawable {
  2546. public:
  2547.     virtual void draw(ObjectContainer& container) const = 0;
  2548.     virtual ~Drawable() = default;
  2549. };
  2550.    
  2551. class Document : public ObjectContainer {
  2552. public:
  2553.    
  2554.     void add_ptr(std::unique_ptr<Object>&& obj) override {
  2555.         objects_.emplace_back(std::move(obj));
  2556.     }
  2557.    
  2558.     void render(std::ostream& out) const;
  2559.    
  2560. };
  2561.    
  2562. }//end namespace svg
  2563. -----------------------------------------------------------------------
  2564. transport_catalogue.cpp
  2565. -----------------------------------------------------------------------
  2566. #include "transport_catalogue.h"
  2567. #include <execution>
  2568.  
  2569. namespace transport_catalogue {  
  2570.    
  2571. void TransportCatalogue::add_stop(Stop&& stop) {
  2572.     stops.push_back(std::move(stop));
  2573.     Stop* stop_buf = &stops.back();
  2574.     stopname_to_stop.insert(transport_catalogue::StopMap::value_type(stop_buf->name, stop_buf));
  2575. }
  2576.  
  2577. void TransportCatalogue::add_bus(Bus&& bus) {
  2578.     Bus* bus_buf;
  2579.    
  2580.     buses.push_back(std::move(bus));
  2581.     bus_buf = &buses.back();
  2582.     busname_to_bus.insert(BusMap::value_type(bus_buf->name, bus_buf));
  2583.  
  2584.     for (Stop* stop : bus_buf->stops) {
  2585.          stop->buses.push_back(bus_buf);
  2586.     }
  2587.    
  2588.     bus_buf->route_length = get_distance_to_bus(bus_buf);
  2589. }
  2590.  
  2591. void TransportCatalogue::add_distance(const std::vector<Distance>& distances) {
  2592.     for (auto distance : distances){
  2593.         auto dist_pair = std::make_pair(distance.start, distance.end);
  2594.         distance_to_stop.insert(DistanceMap::value_type(dist_pair, distance.distance));
  2595.     }
  2596. }
  2597.  
  2598. Bus* TransportCatalogue::get_bus(std::string_view bus_name) {  
  2599.     if(busname_to_bus.empty()){
  2600.         return nullptr;
  2601.     }
  2602.    
  2603.     try{
  2604.         return busname_to_bus.at(bus_name);
  2605.     }
  2606.     catch(const std::out_of_range &e){
  2607.         return nullptr;
  2608.     }
  2609. }
  2610.  
  2611. Stop* TransportCatalogue::get_stop(std::string_view stop_name) {
  2612.     if(stopname_to_stop.empty()){
  2613.         return nullptr;
  2614.     }
  2615.    
  2616.     try {
  2617.         return stopname_to_stop.at(stop_name);
  2618.     } catch(const std::out_of_range &e) {
  2619.         return nullptr;
  2620.     }
  2621. }
  2622.    
  2623. BusMap TransportCatalogue::get_busname_to_bus() const {
  2624.     return busname_to_bus;
  2625. }
  2626.    
  2627. StopMap TransportCatalogue::get_stopname_to_stop() const {
  2628.     return stopname_to_stop;
  2629. }
  2630.  
  2631. std::unordered_set<const Stop*> TransportCatalogue::get_uniq_stops(Bus* bus) {
  2632.     std::unordered_set<const Stop*> unique_stops;
  2633.    
  2634.     unique_stops.insert(bus->stops.begin(), bus->stops.end());
  2635.    
  2636.     return unique_stops;
  2637. }
  2638.  
  2639. double TransportCatalogue::get_length(Bus* bus) {
  2640.     return transform_reduce(next(bus->stops.begin()),
  2641.                             bus->stops.end(),
  2642.                             bus->stops.begin(),
  2643.                             0.0,
  2644.                             std::plus<>{},
  2645.                             [](const Stop* lhs, const Stop* rhs) {
  2646.                                 return geo::compute_distance({(*lhs).latitude,
  2647.                                                         (*lhs).longitude}, {(*rhs).latitude,
  2648.                                                                               (*rhs).longitude});
  2649.                             });
  2650. }
  2651.  
  2652. std::unordered_set<const Bus*> TransportCatalogue::stop_get_uniq_buses(Stop* stop){    
  2653.     std::unordered_set<const Bus*> unique_stops;    
  2654.      
  2655.     unique_stops.insert(stop->buses.begin(), stop->buses.end());  
  2656.    
  2657.     return unique_stops;
  2658. }
  2659.  
  2660. size_t TransportCatalogue::get_distance_stop(const Stop* begin, const Stop* finish) {
  2661.     if(distance_to_stop.empty()){
  2662.         return 0;
  2663.     }
  2664.    
  2665.     try {
  2666.        
  2667.         auto dist_pair = std::make_pair(begin, finish);
  2668.         return distance_to_stop.at(dist_pair);
  2669.        
  2670.     } catch(const std::out_of_range &e) {
  2671.        
  2672.         try {
  2673.             auto dist_pair = std::make_pair(finish, begin);
  2674.             return distance_to_stop.at(dist_pair);
  2675.         } catch(const std::out_of_range &e) {
  2676.             return 0;    
  2677.         }
  2678.        
  2679.     }
  2680. }
  2681.  
  2682. size_t TransportCatalogue::get_distance_to_bus(Bus* bus) {
  2683.     size_t distance = 0;
  2684.     auto stops_size = bus->stops.size() - 1;
  2685.     for (int i = 0; i < static_cast<int>(stops_size); i++) {
  2686.         distance += get_distance_stop(bus->stops[i], bus->stops[i+1]);
  2687.     }
  2688.     return distance;
  2689. }
  2690.    
  2691. }//end namespace transport_catalogue
  2692. -----------------------------------------------------------------------
  2693. transport_catalogue.h
  2694. -----------------------------------------------------------------------
  2695. #pragma once
  2696. #include <deque>
  2697. #include <string>
  2698. #include <vector>
  2699. #include <iomanip>
  2700. #include <iostream>
  2701. #include <unordered_set>
  2702. #include <unordered_map>
  2703.  
  2704. #include "domain.h"
  2705.  
  2706. using namespace domain;
  2707.  
  2708. namespace transport_catalogue {  
  2709.  
  2710. struct DistanceHasher {
  2711.     std::hash<const void*> hasher;
  2712.    
  2713.     std::size_t operator()(const std::pair<const Stop*, const Stop*> pair_stops) const noexcept {
  2714.         auto hash_1 = static_cast<const void*>(pair_stops.first);
  2715.         auto hash_2 = static_cast<const void*>(pair_stops.second);
  2716.         return hasher(hash_1) * 17 + hasher(hash_2);
  2717.     }  
  2718. };
  2719.    
  2720. typedef  std::unordered_map<std::string_view, Stop*> StopMap;
  2721. typedef  std::unordered_map<std::string_view, Bus*> BusMap;
  2722. typedef  std::unordered_map<std::pair<const Stop*, const  Stop*>, int, DistanceHasher> DistanceMap;
  2723.  
  2724. class TransportCatalogue {
  2725. public:      
  2726.     void add_bus(Bus&& bus);
  2727.     void add_stop(Stop&& stop);
  2728.     void add_distance(const std::vector<Distance>& distances);
  2729.    
  2730.     Bus* get_bus(std::string_view bus_name);
  2731.     Stop* get_stop(std::string_view stop_name);
  2732.     BusMap get_busname_to_bus() const;
  2733.     StopMap get_stopname_to_stop() const;
  2734.    
  2735.     std::unordered_set<const Bus*> stop_get_uniq_buses(Stop* stop);    
  2736.     std::unordered_set<const Stop*> get_uniq_stops(Bus* bus);
  2737.     double get_length(Bus* bus);
  2738.    
  2739.     size_t get_distance_stop(const Stop* start, const Stop* finish);
  2740.     size_t get_distance_to_bus(Bus* bus);
  2741.    
  2742. private:    
  2743.     std::deque<Stop> stops;
  2744.     StopMap stopname_to_stop;
  2745.    
  2746.     std::deque<Bus> buses;
  2747.     BusMap busname_to_bus;
  2748.    
  2749.     DistanceMap distance_to_stop;
  2750.    
  2751. };
  2752.    
  2753. }//end namespace transport_catalogue
Advertisement
Add Comment
Please, Sign In to add comment