C/C++ API Reference
Loading...
Searching...
No Matches
dynamic_deque.h
1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <cstddef>
17#include <cstdint>
18#include <initializer_list>
19#include <limits>
20#include <memory>
21#include <type_traits>
22#include <utility>
23
24#include "pw_allocator/allocator.h"
25#include "pw_assert/assert.h"
26#include "pw_containers/internal/count_and_capacity.h"
27#include "pw_containers/internal/generic_deque.h"
28#include "pw_numeric/saturating_arithmetic.h"
29
30namespace pw {
31
33
36
56template <typename ValueType, typename SizeType = uint16_t>
58 DynamicDeque<ValueType, SizeType>,
59 ValueType,
60 containers::internal::CountAndCapacity<SizeType>> {
61 private:
64 ValueType,
65 containers::internal::CountAndCapacity<SizeType>>;
66
67 public:
68 using typename Base::const_iterator;
69 using typename Base::const_pointer;
70 using typename Base::const_reference;
71 using typename Base::difference_type;
72 using typename Base::iterator;
73 using typename Base::pointer;
74 using typename Base::reference;
75 using typename Base::size_type;
76 using typename Base::value_type;
77
79
84 constexpr DynamicDeque(Allocator& allocator) noexcept
85 : Base(0), allocator_(&allocator), buffer_(nullptr) {}
86
87 DynamicDeque(const DynamicDeque&) = delete;
88 DynamicDeque& operator=(const DynamicDeque&) = delete;
89
93 constexpr DynamicDeque(DynamicDeque&& other) noexcept
94 : allocator_(other.allocator_), buffer_(other.buffer_) {
95 other.buffer_ = nullptr; // clean other's buffer_, but not its allocator_
96 Base::MoveAssignIndices(other);
97 }
98
99 DynamicDeque& operator=(DynamicDeque&& other) noexcept;
100
102
103 // Provide try_* versions of functions that return false if allocation fails.
104 using Base::try_assign;
105 using Base::try_emplace;
106 using Base::try_emplace_back;
107 using Base::try_emplace_front;
108 using Base::try_insert;
109 using Base::try_push_back;
110 using Base::try_push_front;
111 using Base::try_resize;
112
113 // The GenericDeque's input iterator insert implementation emplaces items one
114 // at a time, which is inefficient. For DynamicDeque, use a more efficient
115 // implementation that inserts all items into a temporary DynamicDeque first.
116 template <typename InputIt,
117 typename = containers::internal::EnableIfInputIterator<InputIt>>
118 iterator insert(const_iterator pos, InputIt first, InputIt last);
119
120 iterator insert(const_iterator pos, const value_type& value) {
121 return Base::insert(pos, value);
122 }
123
124 iterator insert(const_iterator pos, value_type&& value) {
125 return Base::insert(pos, std::move(value));
126 }
127
128 iterator insert(const_iterator pos,
129 size_type count,
130 const value_type& value) {
131 return Base::insert(pos, count, value);
132 }
133
134 iterator insert(const_iterator pos, std::initializer_list<value_type> ilist) {
135 return Base::insert(pos, ilist);
136 }
137
148 [[nodiscard]] bool try_reserve(size_type new_capacity);
149
151 void reserve(size_type new_capacity) { PW_ASSERT(try_reserve(new_capacity)); }
152
162 [[nodiscard]] bool try_reserve_exact(size_type new_capacity) {
163 return new_capacity <= Base::capacity() || IncreaseCapacity(new_capacity);
164 }
165
167 void reserve_exact(size_type new_capacity) {
168 PW_ASSERT(try_reserve_exact(new_capacity));
169 }
170
173
174 constexpr size_type max_size() const noexcept {
175 return std::numeric_limits<size_type>::max();
176 }
177
179 constexpr allocator_type& get_allocator() const { return *allocator_; }
180
182 void swap(DynamicDeque& other) noexcept {
183 Base::SwapIndices(other);
184 std::swap(allocator_, other.allocator_);
185 std::swap(buffer_, other.buffer_);
186 }
187
188 private:
189 friend Base;
190
191 template <typename, typename>
192 friend class DynamicVector; // Allow direct access to data()
193
194 static constexpr bool kFixedCapacity = false; // uses dynamic allocation
195
196 pointer data() { return std::launder(reinterpret_cast<pointer>(buffer_)); }
197 const_pointer data() const {
198 return std::launder(reinterpret_cast<const_pointer>(buffer_));
199 }
200
201 [[nodiscard]] bool IncreaseCapacity(size_type new_capacity);
202
203 size_type GetNewCapacity(const size_type new_size) {
204 // For the initial allocation, allocate at least 4 words worth of items.
205 if (Base::capacity() == 0) {
206 return std::max(size_type{4 * sizeof(void*) / sizeof(value_type)},
207 new_size);
208 }
209 // Double the capacity. May introduce other allocation policies later.
210 return std::max(mul_sat(Base::capacity(), size_type{2}), new_size);
211 }
212
213 bool ReallocateBuffer(size_type new_capacity);
214
215 Allocator* allocator_;
216 std::byte* buffer_; // raw array for in-place construction and destruction
217};
218
219template <typename ValueType, typename SizeType>
220DynamicDeque<ValueType, SizeType>& DynamicDeque<ValueType, SizeType>::operator=(
221 DynamicDeque&& other) noexcept {
222 Base::clear();
223 allocator_->Deallocate(buffer_);
224
225 allocator_ = other.allocator_; // The other deque keeps its allocator
226 buffer_ = other.buffer_;
227 other.buffer_ = nullptr;
228
229 Base::MoveAssignIndices(other);
230 return *this;
231}
232
233template <typename ValueType, typename SizeType>
234DynamicDeque<ValueType, SizeType>::~DynamicDeque() {
235 Base::clear();
236 allocator_->Deallocate(buffer_);
237}
238
239template <typename ValueType, typename SizeType>
241 return new_capacity <= Base::capacity() ||
242 IncreaseCapacity(GetNewCapacity(new_capacity)) ||
243 IncreaseCapacity(new_capacity);
244}
245
246template <typename ValueType, typename SizeType>
248 size_type new_capacity) {
249 // Try resizing the existing array. Only works if inserting at the end.
250 if (buffer_ != nullptr && Base::CanExtendBuffer() &&
251 allocator_->Resize(buffer_, new_capacity * sizeof(value_type))) {
252 Base::HandleExtendedBuffer(new_capacity);
253 return true;
254 }
255
256 // Allocate a new array and move items to it.
257 return ReallocateBuffer(new_capacity);
258}
259
260template <typename ValueType, typename SizeType>
262 if (Base::size() == Base::capacity()) {
263 return; // Nothing to do; deque is full or buffer_ is nullptr
264 }
265
266 if (Base::empty()) { // Empty deque, but a buffer_ is allocated; free it
267 allocator_->Deallocate(buffer_);
268 buffer_ = nullptr;
269 Base::HandleShrunkBuffer(0);
270 return;
271 }
272
273 // Attempt to shrink if buffer if possible, and reallocate it if needed.
274 //
275 // If there are unused slots at the start, could shift back and Resize()
276 // instead of calling ReallocateBuffer(), but may not be worth the complexity.
277 if (Base::CanShrinkBuffer() &&
278 allocator_->Resize(buffer_, Base::size() * sizeof(value_type))) {
279 Base::HandleShrunkBuffer(Base::size());
280 } else {
281 ReallocateBuffer(Base::size());
282 }
283}
284
285template <typename ValueType, typename SizeType>
287 size_type new_capacity) {
288 std::byte* new_buffer = static_cast<std::byte*>(
289 allocator_->Allocate(allocator::Layout::Of<value_type[]>(new_capacity)));
290 if (new_buffer == nullptr) {
291 return false;
292 }
293
294 pointer dest = std::launder(reinterpret_cast<pointer>(new_buffer));
295 auto [data_1, data_2] = Base::contiguous_data();
296
297 if constexpr (std::is_move_constructible_v<value_type>) {
298 dest = std::uninitialized_move(data_1.begin(), data_1.end(), dest);
299 std::uninitialized_move(data_2.begin(), data_2.end(), dest);
300 } else { // if it can't be moved, try copying
301 dest = std::uninitialized_copy(data_1.begin(), data_1.end(), dest);
302 std::uninitialized_copy(data_2.begin(), data_2.end(), dest);
303 }
304
305 std::destroy(data_1.begin(), data_1.end());
306 std::destroy(data_2.begin(), data_2.end());
307
308 allocator_->Deallocate(buffer_);
309 buffer_ = new_buffer;
310
311 Base::HandleNewBuffer(new_capacity);
312 return true;
313}
314
315template <typename ValueType, typename SizeType>
316template <typename InputIt, typename>
317typename DynamicDeque<ValueType, SizeType>::iterator
318DynamicDeque<ValueType, SizeType>::insert(const_iterator pos,
319 InputIt first,
320 InputIt last) {
321 // Can't safely check std::distance for InputIterator. Use a workaround.
322 if constexpr (std::is_same_v<std::input_iterator_tag,
323 typename std::iterator_traits<
324 InputIt>::iterator_category>) {
325 // Read into a temporary deque so the items can be counted. Then, move into
326 // this deque in one operation. This way, existing items are shifted once to
327 // their final positions, instead of shifting N times for repeated inserts.
328 DynamicDeque temp(*allocator_);
329 temp.assign(first, last);
330 return Base::insert(pos,
331 std::make_move_iterator(temp.data()),
332 std::make_move_iterator(temp.data() + temp.size()));
333 } else { // Use the efficient base implementation for forward iterators.
334 return Base::insert(pos, first, last);
335 }
336}
337
338} // namespace pw
Definition: allocator.h:36
Definition: dynamic_deque.h:60
Definition: dynamic_vector.h:53
Definition: generic_deque.h:180
constexpr size_type capacity() const noexcept
Returns the maximum number of elements in the deque.
Definition: generic_deque.h:69
void reserve(size_type new_capacity)
Increases capacity() to at least new_capacity. Crashes on failure.
Definition: dynamic_deque.h:151
void reserve_exact(size_type new_capacity)
Increases capacity() to exactly new_capacity. Crashes on failure.
Definition: dynamic_deque.h:167
constexpr DynamicDeque(DynamicDeque &&other) noexcept
Definition: dynamic_deque.h:93
void swap(DynamicDeque &other) noexcept
Swaps the contents of two deques. No allocations occur.
Definition: dynamic_deque.h:182
bool try_reserve(size_type new_capacity)
Definition: dynamic_deque.h:240
bool try_assign(size_type count, const value_type &value)
Definition: generic_deque.h:615
void shrink_to_fit()
Attempts to reduce capacity() to size(). Not guaranteed to succeed.
Definition: dynamic_deque.h:261
constexpr allocator_type & get_allocator() const
Returns the deque's allocator.
Definition: dynamic_deque.h:179
bool try_reserve_exact(size_type new_capacity)
Definition: dynamic_deque.h:162
constexpr DynamicDeque(Allocator &allocator) noexcept
Definition: dynamic_deque.h:84
iterator insert(const_iterator pos, const value_type &value)
Definition: generic_deque.h:355
std::optional< iterator > try_emplace(const_iterator pos, Args &&... args)
std::optional< iterator > try_insert(const_iterator pos, const value_type &value)
Definition: generic_deque.h:465
constexpr T mul_sat(T lhs, T rhs) noexcept
Definition: saturating_arithmetic.h:75
The Pigweed namespace.
Definition: alignment.h:27