userver: userver/formats/bson/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/bson/iterator.hpp
4/// @brief @copybrief formats::bson::Iterator
5
6#include <iterator>
7#include <optional>
8#include <string>
9#include <type_traits>
10#include <unordered_map>
11#include <variant>
12#include <vector>
13
14#include <userver/formats/bson/types.hpp>
15#include <userver/formats/common/iterator_direction.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace formats::bson {
20
21/// Iterator for BSON values
22template <typename ValueType, common::IteratorDirection Direction = common::IteratorDirection::kForward>
23class Iterator final {
24public:
25 using iterator_category = std::forward_iterator_tag;
26 using difference_type = ptrdiff_t;
27 using value_type = std::remove_const_t<ValueType>;
28 using reference = ValueType&;
29 using pointer = ValueType*;
30
31 /// @cond
32 using NativeIter = std::variant<
33 impl::ParsedArray::const_iterator,
34 impl::ParsedArray::const_reverse_iterator,
35 impl::ParsedDocument::const_iterator>;
36
37 Iterator();
38 Iterator(impl::ValueImpl&, NativeIter);
39 /// @endcond
40
41 Iterator(const Iterator&);
42 Iterator(Iterator&&) noexcept;
43 Iterator& operator=(const Iterator&);
44 Iterator& operator=(Iterator&&) noexcept;
45
46 /// @name Forward iterator requirements
47 /// @{
48 Iterator operator++(int);
49 Iterator& operator++();
50 reference operator*() const;
51 pointer operator->() const;
52
53 bool operator==(const Iterator&) const;
54 bool operator!=(const Iterator&) const;
55 /// @}
56
57 /// @brief Returns name of currently selected document field
58 /// @throws TypeMismatchException if iterated value is not a document
59 template <typename T = void>
60 std::string GetName() const {
61 static_assert(
62 Direction == common::IteratorDirection::kForward,
63 "Reverse iterator should be used only on arrays or null, "
64 "they do not have GetName()"
65 );
66 return GetNameImpl();
67 }
68
69 /// @brief Returns index of currently selected array element
70 /// @throws TypeMismatchException if iterated value is not an array
71 uint32_t GetIndex() const;
72
73private:
74 std::string GetNameImpl() const;
75 void UpdateValue() const;
76
77 impl::ValueImpl* iterable_;
78 NativeIter it_;
79 mutable std::optional<value_type> current_;
80};
81
82} // namespace formats::bson
83
84USERVER_NAMESPACE_END