userver: userver/utils/slot_map.hpp Source File
Loading...
Searching...
No Matches
slot_map.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/slot_map.hpp
4/// @brief @copybrief utils::SlotMap
5
6#include <concepts>
7#include <cstddef>
8#include <deque>
9#include <limits>
10#include <ranges>
11#include <utility>
12#include <variant>
13
14#include <userver/compiler/impl/lifetime.hpp>
15#include <userver/utils/assert.hpp>
16#include <userver/utils/fast_scope_guard.hpp>
17#include <userver/utils/impl/intrusive_link_mode.hpp>
18#include <userver/utils/meta.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22namespace utils {
23
24namespace impl::slot_map {
25
26template <typename Range>
27concept HasCapacity = requires(Range range) {
28 {
29 range.capacity()
30 } -> std::integral;
31};
32
33template <typename Range>
34concept Indexable = requires(Range range, std::size_t index) {
35 {
36 range[index]
37 } -> std::convertible_to<std::ranges::range_reference_t<Range&>>;
38};
39
40inline constexpr std::size_t kFreeListEnd = std::numeric_limits<std::size_t>::max();
41
42struct FreeNode final {
43 constexpr explicit FreeNode(std::size_t next_index) noexcept
44 : next_index(next_index)
45 {}
46
47 std::size_t next_index{kFreeListEnd};
48};
49
50} // namespace impl::slot_map
51
52/// @ingroup userver_containers
53///
54/// @brief A minimalistic slot-map container adaptor.
55///
56/// Each slot holds either a live value of type `T` or a free-list node.
57/// Erased slots are recycled so that `emplace` reuses them before allocating new storage.
58///
59/// Guarantees:
60///
61/// - `operator[](std::size_t)` is O(1);
62/// - `emplace` and `insert` are amortized O(1) (assuming that `Container` provides this guarantee);
63/// - `erase` is O(1);
64/// - `size()` and `empty()` are O(1);
65/// - iterators returned by `AliveItems()` ARE invalidated by `emplace`, `insert`,
66/// `insert_range`, and `erase`, regardless of the underlying `Container`.
67///
68/// If `Container` is `std::deque` or another reference-stable container, then inserted elements have reference
69/// stability; otherwise elements may move around on `emplace` and `insert*`, and `T` should be movable.
70///
71/// `Container` template is instantiated with an internal value type; the resulting type must:
72///
73/// - be a `std::ranges::forward_range` and `std::ranges::sized_range`;
74/// - support `operator[](std::size_t)` with computational complexity O(1);
75/// - support `emplace_back`, forwarding arbitrary `Args&&...` to the value;
76/// - support `std::ranges::size` with computational complexity O(1).
77///
78/// For example, `std::deque`, `std::vector`, `boost::small_vector` satisfy those requirements.
79///
80/// @note Not thread-safe.
81template <typename T, template <typename...> typename Container = std::deque>
82class SlotMap final {
83 using Slot = std::variant<T, impl::slot_map::FreeNode>;
84
85 static_assert(std::ranges::forward_range<Container<Slot>&>);
86 static_assert(std::ranges::forward_range<const Container<Slot>&>);
87 static_assert(std::ranges::sized_range<const Container<Slot>&>);
88 static_assert(impl::slot_map::Indexable<Container<Slot>&>);
89 static_assert(impl::slot_map::Indexable<const Container<Slot>&>);
90
91public:
92 /// @brief Result of an `emplace` or `insert` call.
94 T& element; ///< Reference to the newly inserted element.
95 std::size_t index; ///< Stable index of the newly inserted element.
96 };
97
98 /// @brief Constructs an empty SlotMap.
99 SlotMap() = default;
100
101 /// @brief Constructs a SlotMap from the elements in `[first, last)`.
102 template <std::input_iterator It, std::sentinel_for<It> Sentinel>
103 SlotMap(It first, Sentinel last) {
104 insert_range(std::ranges::subrange(std::move(first), std::move(last)));
105 }
106
107 SlotMap(const SlotMap&) = default;
108 SlotMap& operator=(const SlotMap&) = default;
109
110 /// @brief Moves the contents of @a other, leaving it empty and reusable.
111 SlotMap(SlotMap&& other) noexcept
112 : slots_(std::move(other.slots_)),
113 free_list_head_(std::exchange(other.free_list_head_, impl::slot_map::kFreeListEnd)),
114 free_list_size_(std::exchange(other.free_list_size_, 0))
115 {
116 other.slots_ = Container<Slot>{};
117 }
118
119 /// @brief Moves the contents of @a other, leaving it empty and reusable. Self-move is a no-op.
120 SlotMap& operator=(SlotMap&& other) noexcept {
121 if (this != &other) {
122 slots_ = std::move(other.slots_);
123 free_list_head_ = std::exchange(other.free_list_head_, impl::slot_map::kFreeListEnd);
124 free_list_size_ = std::exchange(other.free_list_size_, 0);
125 other.slots_ = Container<Slot>{};
126 }
127 return *this;
128 }
129
130 ~SlotMap() = default;
131
132 /// @brief Constructs a new element in-place and returns a reference to it and its stable index.
133 ///
134 /// If there are free (erased) slots, one is reused; otherwise new storage is allocated.
135 ///
136 /// @note Invalidates all iterators returned by `AliveItems()`.
137 /// Does not invalidate references to existing elements if the underlying container supports it, e.g. `std::deque`.
138 template <typename... Args>
139 InsertionResult emplace(Args&&... args) USERVER_IMPL_LIFETIME_BOUND {
140 if (const auto entry = TryPopFromFreeList(); entry.slot != nullptr) {
141 try {
142 T& element = entry.slot->template emplace<T>(std::forward<Args>(args)...);
143 return {element, entry.index};
144 } catch (...) {
145 EraseAndPushToFreeList(entry);
146 throw;
147 }
148 }
149
150 const std::size_t index = std::ranges::size(slots_);
151 Slot& slot = slots_.emplace_back(std::in_place_type<T>, std::forward<Args>(args)...);
152 auto* const value = std::get_if<T>(&slot);
153 UASSERT(value != nullptr);
154 return {*value, index};
155 }
156
157 /// @brief Inserts a copy of @a value and returns a reference to it and its stable index.
158 ///
159 /// @note Invalidates all iterators returned by `AliveItems()`.
160 /// Does not invalidate references to existing elements if the underlying container supports it, e.g. `std::deque`.
161 InsertionResult insert(const T& value) USERVER_IMPL_LIFETIME_BOUND { return emplace(value); }
162
163 /// @brief Inserts @a value by move and returns a reference to it and its stable index.
164 ///
165 /// @note Invalidates all iterators returned by `AliveItems()`.
166 /// Does not invalidate references to existing elements if the underlying container supports it, e.g. `std::deque`.
167 InsertionResult insert(T&& value) USERVER_IMPL_LIFETIME_BOUND { return emplace(std::move(value)); }
168
169 /// @brief Inserts all elements from @a range.
170 ///
171 /// Provides a basic exception guarantee: if an element's constructor throws,
172 /// all previously inserted elements remain valid and the map is left in a
173 /// consistent state.
174 ///
175 /// @note Invalidates all iterators returned by `AliveItems()`.
176 /// Does not invalidate references to existing elements if the underlying container supports it, e.g. `std::deque`.
177 template <std::ranges::input_range Range>
178 void insert_range(Range&& range) {
179 for (auto&& elem : std::forward<Range>(range)) {
180 emplace(std::forward<decltype(elem)>(elem));
181 }
182 }
183
184 /// @brief Returns the number of live elements.
185 [[nodiscard]] std::size_t size() const noexcept { return std::ranges::size(slots_) - free_list_size_; }
186
187 /// @brief Returns true if there are no live elements.
188 [[nodiscard]] bool empty() const noexcept { return size() == 0; }
189
190 /// @brief Returns the total number of allocated slots (live + free).
191 ///
192 /// This is the size of the backing storage. It never shrinks.
193 [[nodiscard]] std::size_t capacity() const noexcept {
194 if constexpr (impl::slot_map::HasCapacity<const Container<Slot>&>) {
195 return slots_.capacity();
196 } else {
197 return std::ranges::size(slots_);
198 }
199 }
200
201 /// @brief Calls `reserve` on the underlying container.
202 void reserve(std::size_t capacity)
203 requires meta::IsReservable<Container<Slot>>
204 {
205 slots_.reserve(capacity);
206 }
207
208 /// @brief Returns a reference to the live element at @a index.
209 ///
210 /// Precondition: the slot at @a index holds a live element (was not erased).
211 T& operator[](std::size_t index) noexcept USERVER_IMPL_LIFETIME_BOUND {
212 UASSERT(index < std::ranges::size(slots_));
213 auto* const value = std::get_if<T>(&slots_[index]);
214 UASSERT(value != nullptr);
215 return *value;
216 }
217
218 /// @overload
219 const T& operator[](std::size_t index) const noexcept USERVER_IMPL_LIFETIME_BOUND {
220 UASSERT(index < std::ranges::size(slots_));
221 const auto* const value = std::get_if<T>(&slots_[index]);
222 UASSERT(value != nullptr);
223 return *value;
224 }
225
226 /// @brief Destroys the element at @a index and recycles the slot.
227 ///
228 /// If the slot at @a index is already free (was previously erased), this is a no-op.
229 ///
230 /// @returns the number of erased elements: `1` if a live element was erased,
231 /// `0` if the slot was already free.
232 ///
233 /// @note Invalidates all iterators returned by `AliveItems()`.
234 /// Does NOT invalidate references to other live elements.
235 std::size_t erase(std::size_t index) {
236 UASSERT(index < std::ranges::size(slots_));
237 auto& slot = slots_[index];
238 if (std::get_if<T>(&slot) == nullptr) {
239 return 0;
240 }
241 EraseAndPushToFreeList({.slot = &slot, .index = index});
242 return 1;
243 }
244
245 /// @brief Returns a view over live (non-erased) elements, yielding `T&` references.
246 ///
247 /// @warning Iterators of the returned view are invalidated by `emplace`, `insert`,
248 /// `insert_range`, and `erase`. References to elements remain valid.
249 [[nodiscard]] std::ranges::forward_range auto AliveItems() noexcept USERVER_IMPL_LIFETIME_BOUND {
250 return std::ranges::ref_view(slots_) | std::views::filter(IsLive{}) | std::views::transform(ToValue{});
251 }
252
253 /// @overload
254 [[nodiscard]] std::ranges::forward_range auto AliveItems() const noexcept USERVER_IMPL_LIFETIME_BOUND {
255 return std::ranges::ref_view(slots_) | std::views::filter(IsLive{}) | std::views::transform(ToConstValue{});
256 }
257
258private:
259 struct IsLive {
260 bool operator()(const Slot& slot) const noexcept { return std::holds_alternative<T>(slot); }
261 };
262
263 struct ToValue {
264 T& operator()(Slot& slot) const noexcept {
265 auto* const value = std::get_if<T>(&slot);
266 UASSERT(value != nullptr);
267 return *value;
268 }
269 };
270
271 struct ToConstValue {
272 const T& operator()(const Slot& slot) const noexcept {
273 const auto* const value = std::get_if<T>(&slot);
274 UASSERT(value != nullptr);
275 return *value;
276 }
277 };
278
279 struct FreeListEntry final {
280 Slot* slot;
281 std::size_t index;
282 };
283
284 FreeListEntry TryPopFromFreeList() noexcept {
285 const auto index = free_list_head_;
286
287 if (index == impl::slot_map::kFreeListEnd) {
288 return {.slot = nullptr, .index = impl::slot_map::kFreeListEnd};
289 }
290
291 Slot& slot = slots_[index];
292 const auto* const node = std::get_if<impl::slot_map::FreeNode>(&slot);
293 UASSERT(node != nullptr);
294 free_list_head_ = node->next_index;
295 --free_list_size_;
296 return {.slot = &slot, .index = index};
297 }
298
299 void EraseAndPushToFreeList(FreeListEntry entry) noexcept {
300 UASSERT(entry.slot != nullptr);
301 UASSERT(entry.slot == &slots_[entry.index]);
302 entry.slot->template emplace<impl::slot_map::FreeNode>(free_list_head_);
303 free_list_head_ = entry.index;
304 ++free_list_size_;
305 }
306
307 Container<Slot> slots_;
308 std::size_t free_list_head_{impl::slot_map::kFreeListEnd};
309 std::size_t free_list_size_{0};
310};
311
312} // namespace utils
313
314USERVER_NAMESPACE_END