userver: userver/formats/json/iterator.hpp Source File
Loading...
Searching...
No Matches
iterator.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/iterator.hpp
4/// @brief @copybrief formats::json::Iterator
5
6#include <iterator>
7#include <optional>
8#include <string>
9
10#include <userver/formats/common/iterator_direction.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace formats::json {
15
16/// @brief Iterator for `formats::json::Value`
17template <typename Traits, common::IteratorDirection Direction = common::IteratorDirection::kForward>
18class Iterator final {
19public:
20 using iterator_category = std::forward_iterator_tag;
21 using difference_type = std::ptrdiff_t;
22 using value_type = typename Traits::ValueType;
23 using reference = typename Traits::Reference;
24 using pointer = typename Traits::Pointer;
25
26 using ContainerType = typename Traits::ContainerType;
27
28 Iterator(ContainerType container, int pos);
29
30 Iterator(const Iterator& other);
31 Iterator(Iterator&& other) noexcept;
32 Iterator& operator=(const Iterator& other);
33 Iterator& operator=(Iterator&& other) noexcept;
34
35 ~Iterator();
36
37 Iterator operator++(int);
38 Iterator& operator++();
39 reference operator*() const;
40 pointer operator->() const;
41
42 bool operator==(const Iterator& other) const;
43 bool operator!=(const Iterator& other) const;
44
45 /// @brief Returns name of the referenced field
46 /// @throws `TypeMismatchException` if iterated value is not an object
47 template <typename T = void>
48 std::string GetName() const {
49 static_assert(
50 Direction == common::IteratorDirection::kForward,
51 "Reverse iterator should be used only on arrays or null, "
52 "they do not have GetName()"
53 );
54 return GetNameImpl();
55 }
56
57 /// @brief Returns index of the referenced field
58 /// @throws `TypeMismatchException` if iterated value is not an array
60
61private:
62 std::string GetNameImpl() const;
63 Iterator(ContainerType&& container, int type, int pos) noexcept;
64
65 void UpdateValue() const;
66
67 /// Container being iterated
68 ContainerType container_;
69 /// Internal container type
70 int type_;
71 /// Position inside container being iterated
72 int pos_;
73 // Temporary object replaced on every value access.
74 mutable std::optional<value_type> current_;
75};
76
77} // namespace formats::json
78
79USERVER_NAMESPACE_END