Commit | Line | Data |
---|---|---|
9ded8453 FD |
1 | /* |
2 | * Copyright (c) 2022 Francis Deslauriers <francis.deslauriers@efficios.com> | |
3 | * | |
4 | * SPDX-License-Identifier: MIT | |
5 | */ | |
6 | ||
8aee46a3 PP |
7 | #ifndef BABELTRACE_CPP_COMMON_BT2_COMMON_ITERATOR_HPP |
8 | #define BABELTRACE_CPP_COMMON_BT2_COMMON_ITERATOR_HPP | |
9ded8453 | 9 | |
7ece2fc0 | 10 | #include <cstdint> |
9ded8453 | 11 | #include <iterator> |
9ded8453 FD |
12 | |
13 | #include "cpp-common/optional.hpp" | |
14 | ||
15 | namespace bt2 { | |
16 | ||
17 | template <typename ContainerT, typename ElemT> | |
18 | class CommonIterator | |
19 | { | |
20 | friend ContainerT; | |
21 | ||
22 | public: | |
23 | using difference_type = std::ptrdiff_t; | |
24 | using value_type = ElemT; | |
25 | using pointer = value_type *; | |
26 | using reference = value_type&; | |
27 | using iterator_category = std::input_iterator_tag; | |
28 | ||
29 | private: | |
30 | explicit CommonIterator(const ContainerT container, const uint64_t idx) : | |
31 | _mContainer {container}, _mIdx {idx} | |
32 | { | |
33 | this->_updateCurrentValue(); | |
34 | } | |
35 | ||
36 | public: | |
37 | CommonIterator(const CommonIterator&) = default; | |
38 | CommonIterator(CommonIterator&&) = default; | |
39 | CommonIterator& operator=(const CommonIterator&) = default; | |
40 | CommonIterator& operator=(CommonIterator&&) = default; | |
41 | ||
42 | CommonIterator& operator++() noexcept | |
43 | { | |
44 | ++_mIdx; | |
45 | this->_updateCurrentValue(); | |
46 | return *this; | |
47 | } | |
48 | ||
49 | CommonIterator operator++(int) noexcept | |
50 | { | |
51 | const auto tmp = *this; | |
52 | ||
53 | ++(*this); | |
54 | return tmp; | |
55 | } | |
56 | ||
57 | bool operator==(const CommonIterator& other) const noexcept | |
58 | { | |
59 | return _mIdx == other._mIdx; | |
60 | } | |
61 | ||
62 | bool operator!=(const CommonIterator& other) const noexcept | |
63 | { | |
64 | return !(*this == other); | |
65 | } | |
66 | ||
67 | reference operator*() noexcept | |
68 | { | |
69 | return *_mCurrVal; | |
70 | } | |
71 | ||
72 | pointer operator->() noexcept | |
73 | { | |
74 | return &(*_mCurrVal); | |
75 | } | |
76 | ||
77 | private: | |
78 | void _updateCurrentValue() noexcept | |
79 | { | |
80 | if (_mIdx < _mContainer.size()) { | |
81 | _mCurrVal = _mContainer[_mIdx]; | |
82 | } else { | |
83 | _mCurrVal = nonstd::nullopt; | |
84 | } | |
85 | } | |
86 | ||
87 | nonstd::optional<value_type> _mCurrVal; | |
88 | ContainerT _mContainer; | |
89 | uint64_t _mIdx; | |
90 | }; | |
0ecadeb9 | 91 | |
9ded8453 FD |
92 | } /* namespace bt2 */ |
93 | ||
8aee46a3 | 94 | #endif /* BABELTRACE_CPP_COMMON_BT2_COMMON_ITERATOR_HPP */ |