userver: userver/formats/json/parser/map_parser.hpp Source File
Loading...
Searching...
No Matches
map_parser.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/parser/map_parser.hpp
4/// @brief @copybrief formats::json::parser::MapParser
5/// @ingroup userver_universal
6
7#include <userver/formats/json/parser/typed_parser.hpp>
8
9USERVER_NAMESPACE_BEGIN
10
11namespace formats::json::parser {
12
13/// @brief SAX parser that fills maps from JSON objects.
14template <typename Map, typename ValueParser>
15class MapParser final : public TypedParser<Map>, public Subscriber<typename Map::mapped_type> {
16public:
17 using Value = typename Map::mapped_type;
18
19 explicit MapParser(ValueParser& value_parser)
20 : value_parser_(value_parser)
21 {}
22
23 void Reset() override { this->state_ = State::kStart; }
24
25 void StartObject() override {
26 switch (state_) {
27 case State::kStart:
28 this->state_ = State::kInside;
29 break;
30
31 case State::kInside:
32 this->Throw("{");
33 }
34 }
35
36 void Key(std::string_view key) override {
37 if (state_ != State::kInside) {
38 this->Throw("object");
39 }
40
41 key_ = key;
42 this->value_parser_.Reset();
43 this->value_parser_.Subscribe(*this);
44 this->parser_state_->PushParser(this->value_parser_.GetParser());
45 }
46
47 void EndObject() override {
48 if (state_ == State::kInside) {
49 this->SetResult(std::move(result_));
50 return;
51 }
52 // impossible?
53 this->Throw("}");
54 }
55
56 std::string Expected() const override {
57 switch (state_) {
58 case State::kInside:
59 return "string";
60
61 case State::kStart:
62 return "object";
63 }
64
65 UINVARIANT(false, "Unexpected parser state");
66 }
67
68private:
69 void OnSend(Value&& value) override { this->result_.emplace(std::move(key_), std::move(value)); }
70
71 std::string GetPathItem() const override { return key_; }
72
73 enum class State {
74 kStart,
75 kInside,
76 };
77 State state_{State::kStart};
78 std::string key_;
79 Map result_;
80 ValueParser& value_parser_;
81};
82
83} // namespace formats::json::parser
84
85USERVER_NAMESPACE_END