userver: userver/formats/json/iterator.hpp Source File
⚠️ This is the documentation for an old userver version. Click here to switch to the latest version.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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 =
18 common::IteratorDirection::kForward>
19class Iterator final {
20 public:
21 using iterator_category = std::forward_iterator_tag;
22 using difference_type = std::ptrdiff_t;
23 using value_type = typename Traits::ValueType;
24 using reference = typename Traits::Reference;
25 using pointer = typename Traits::Pointer;
26
27 using ContainerType = typename Traits::ContainerType;
28
29 Iterator(ContainerType container, int pos);
30
31 Iterator(const Iterator& other);
32 Iterator(Iterator&& other) noexcept;
33 Iterator& operator=(const Iterator& other);
34 Iterator& operator=(Iterator&& other) noexcept;
35
36 ~Iterator();
37
38 Iterator operator++(int);
39 Iterator& operator++();
40 reference operator*() const;
41 pointer operator->() const;
42
43 bool operator==(const Iterator& other) const;
44 bool operator!=(const Iterator& other) const;
45
46 /// @brief Returns name of the referenced field
47 /// @throws `TypeMismatchException` if iterated value is not an object
48 template <typename T = void>
49 std::string GetName() const {
50 static_assert(Direction == common::IteratorDirection::kForward,
51 "Reverse iterator should be used only on arrays or null, "
52 "they do not have GetName()");
53 return GetNameImpl();
54 }
55
56 /// @brief Returns index of the referenced field
57 /// @throws `TypeMismatchException` if iterated value is not an array
59
60 private:
61 std::string GetNameImpl() const;
62 Iterator(ContainerType&& container, int type, int pos) noexcept;
63
64 void UpdateValue() const;
65
66 /// Container being iterated
67 ContainerType container_;
68 /// Internal container type
69 int type_;
70 /// Position inside container being iterated
71 int pos_;
72 // Temporary object replaced on every value access.
73 mutable std::optional<value_type> current_;
74};
75
76} // namespace formats::json
77
78USERVER_NAMESPACE_END