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();
29
30 Iterator(ContainerType container, int pos);
31
32 Iterator(const Iterator& other);
33 Iterator(Iterator&& other) noexcept;
34 Iterator& operator=(const Iterator& other);
35 Iterator& operator=(Iterator&& other) noexcept;
36
37 ~Iterator();
38
39 Iterator operator++(int);
40 Iterator& operator++();
41 reference operator*() const;
42 pointer operator->() const;
43
44 bool operator==(const Iterator& other) const;
45 bool operator!=(const Iterator& other) const;
46
47 /// @brief Returns name of the referenced field
48 /// @throws `TypeMismatchException` if iterated value is not an object
49 /// @deprecated Prefer @ref formats::common::Items "formats::common::Items()" for object iteration.
50 template <typename T = void>
51 std::string GetName() const {
52 static_assert(
53 Direction == common::IteratorDirection::kForward,
54 "Reverse iterator should be used only on arrays or null, "
55 "they do not have GetName()"
56 );
57 return GetNameImpl();
58 }
59
60 /// @brief Returns index of the referenced field
61 /// @throws `TypeMismatchException` if iterated value is not an array
62 /// @deprecated Prefer @ref utils::enumerate for array iteration.
63 /// @see @ref scripts/docs/en/userver/formats.md
64 size_t GetIndex() const;
65
66private:
67 bool IsValid() const;
68 std::string GetNameImpl() const;
69 Iterator(ContainerType&& container, int type, int pos) noexcept;
70
71 void UpdateValue() const;
72
73 /// Container being iterated
74 ContainerType container_;
75 /// Internal container type
76 int type_;
77 /// Position inside container being iterated
78 int pos_;
79 // Temporary object replaced on every value access.
80 mutable std::optional<value_type> current_;
81};
82
83} // namespace formats::json
84
85USERVER_NAMESPACE_END