Commit | Line | Data |
---|---|---|
56862ee2 SM |
1 | /* |
2 | * Copyright (c) 2022 Francis Deslauriers <francis.deslauriers@efficios.com> | |
3 | * Copyright (c) 2023 Philippe Proulx <pproulx@efficios.com> | |
4 | * | |
5 | * SPDX-License-Identifier: MIT | |
6 | */ | |
7 | ||
8 | #ifndef BABELTRACE_CPP_COMMON_BT2_BORROWED_OBJECT_ITERATOR_HPP | |
9 | #define BABELTRACE_CPP_COMMON_BT2_BORROWED_OBJECT_ITERATOR_HPP | |
10 | ||
11 | #include <cstdint> | |
12 | #include <type_traits> | |
13 | #include <utility> | |
14 | ||
15 | #include "common/assert.h" | |
16 | ||
17 | #include "borrowed-object-proxy.hpp" | |
18 | ||
19 | namespace bt2 { | |
20 | ||
21 | /* | |
22 | * An iterator class to iterate an instance of a borrowed object | |
23 | * container of type `ContainerT`. | |
24 | * | |
25 | * `ContainerT` must implement: | |
26 | * | |
27 | * // Returns the number of contained borrowed objects. | |
28 | * std::uint64_t length() const noexcept; | |
29 | * | |
30 | * // Returns the borrowed object at index `i`. | |
31 | * SomeObject operator[](std::uint64_t i) const noexcept; | |
32 | */ | |
33 | template <typename ContainerT> | |
34 | class BorrowedObjectIterator final | |
35 | { | |
36 | friend ContainerT; | |
37 | ||
38 | public: | |
39 | using Object = typename std::remove_reference< | |
40 | decltype(std::declval<ContainerT>()[std::declval<std::uint64_t>()])>::type; | |
41 | ||
42 | private: | |
43 | explicit BorrowedObjectIterator(const ContainerT container, const uint64_t idx) : | |
44 | _mContainer {container}, _mIdx {idx} | |
45 | { | |
46 | } | |
47 | ||
48 | public: | |
49 | BorrowedObjectIterator& operator++() noexcept | |
50 | { | |
51 | ++_mIdx; | |
52 | return *this; | |
53 | } | |
54 | ||
55 | BorrowedObjectIterator operator++(int) noexcept | |
56 | { | |
57 | const auto tmp = *this; | |
58 | ||
59 | ++(*this); | |
60 | return tmp; | |
61 | } | |
62 | ||
63 | bool operator==(const BorrowedObjectIterator& other) const noexcept | |
64 | { | |
65 | BT_ASSERT_DBG(_mContainer.isSame(other._mContainer)); | |
66 | return _mIdx == other._mIdx; | |
67 | } | |
68 | ||
69 | bool operator!=(const BorrowedObjectIterator& other) const noexcept | |
70 | { | |
71 | return !(*this == other); | |
72 | } | |
73 | ||
74 | Object operator*() const noexcept | |
75 | { | |
76 | BT_ASSERT_DBG(_mIdx < _mContainer.length()); | |
77 | return _mContainer[_mIdx]; | |
78 | } | |
79 | ||
80 | BorrowedObjectProxy<Object> operator->() const noexcept | |
81 | { | |
82 | return BorrowedObjectProxy<Object> {(**this).libObjPtr()}; | |
83 | } | |
84 | ||
85 | private: | |
86 | ContainerT _mContainer; | |
87 | std::uint64_t _mIdx; | |
88 | }; | |
89 | ||
90 | } /* namespace bt2 */ | |
91 | ||
92 | #endif /* BABELTRACE_CPP_COMMON_BT2_BORROWED_OBJECT_ITERATOR_HPP */ |