2 * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 * SPDX-License-Identifier: LGPL-2.1-only
8 #ifndef LTTNG_CONTAINER_WRAPPER_H
9 #define LTTNG_CONTAINER_WRAPPER_H
11 #include <common/macros.hpp>
20 * random_access_container_wrapper is a helper to provide an idiomatic C++ interface
21 * from a C container API. ElementAccessorCallable and ElementCountAccessorCallable
22 * are two functors which must be provided to allow access to the underlying elements
23 * of the container and to its size.
25 template <typename ContainerType, typename ElementType, typename ContainerOperations>
26 class random_access_container_wrapper {
27 class _iterator : public std::iterator<std::random_access_iterator_tag, std::size_t> {
29 explicit _iterator(const random_access_container_wrapper& container,
30 std::size_t start_index = 0) :
31 _container(container), _index(start_index)
35 _iterator& operator++() noexcept
41 _iterator& operator--() noexcept
47 _iterator& operator++(int) noexcept
49 auto this_before_increment = *this;
52 return this_before_increment;
55 _iterator& operator--(int) noexcept
61 bool operator==(const _iterator& other) const noexcept
63 return _index == other._index;
66 bool operator!=(const _iterator& other) const noexcept
68 return !(*this == other);
71 typename std::conditional<std::is_pointer<ElementType>::value,
74 operator*() const noexcept
76 return _container[_index];
80 const random_access_container_wrapper& _container;
84 using iterator = _iterator;
87 explicit random_access_container_wrapper(ContainerType container) : _container{ container }
91 iterator begin() noexcept
93 return iterator(*this);
96 iterator end() noexcept
98 return iterator(*this, ContainerOperations::size(_container));
101 std::size_t size() const noexcept
103 return ContainerOperations::size(_container);
106 typename std::conditional<std::is_pointer<ElementType>::value, ElementType, ElementType&>::type
107 operator[](std::size_t index)
109 LTTNG_ASSERT(index < ContainerOperations::size(_container));
110 return ContainerOperations::get(_container, index);
113 typename std::conditional<std::is_pointer<ElementType>::value,
115 const ElementType&>::type
116 operator[](std::size_t index) const
118 LTTNG_ASSERT(index < ContainerOperations::size(_container));
119 return ContainerOperations::get(_container, index);
123 ContainerType _container;
125 } /* namespace utils */
126 } /* namespace lttng */
128 #endif /* LTTNG_CONTAINER_WRAPPER_H */