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/generic_deque.h"
27#include "pw_numeric/saturating_arithmetic.h"
28
29namespace pw {
30
32
35
65template <typename ValueType, typename SizeType = uint16_t>
67 : public containers::internal::
68 GenericDeque<DynamicDeque<ValueType, SizeType>, ValueType, SizeType> {
69 private:
70 using Base = containers::internal::
71 GenericDeque<DynamicDeque<ValueType, SizeType>, ValueType, SizeType>;
72
73 public:
74 using typename Base::const_iterator;
75 using typename Base::const_pointer;
76 using typename Base::const_reference;
77 using typename Base::difference_type;
78 using typename Base::iterator;
79 using typename Base::pointer;
80 using typename Base::reference;
81 using typename Base::size_type;
82 using typename Base::value_type;
83
85
90 constexpr DynamicDeque(Allocator& allocator) noexcept
91 : Base(0), allocator_(&allocator), buffer_(nullptr) {}
92
93 DynamicDeque(const DynamicDeque&) = delete;
94 DynamicDeque& operator=(const DynamicDeque&) = delete;
95
99 constexpr DynamicDeque(DynamicDeque&& other) noexcept
100 : Base(0), allocator_(other.allocator_), buffer_(other.buffer_) {
101 other.buffer_ = nullptr; // clear other's buffer_, but not its allocator_
102 Base::MoveAssignIndices(other);
103 }
104
105 DynamicDeque& operator=(DynamicDeque&& other) noexcept;
106
108
109 // Provide try_* versions of functions that return false if allocation fails.
110 using Base::try_assign;
111 using Base::try_emplace;
112 using Base::try_emplace_back;
113 using Base::try_emplace_front;
114 using Base::try_insert;
115 using Base::try_push_back;
116 using Base::try_push_front;
117 using Base::try_resize;
118
119 // The GenericDeque's input iterator insert implementation emplaces items one
120 // at a time, which is inefficient. For DynamicDeque, use a more efficient
121 // implementation that inserts all items into a temporary DynamicDeque first.
122 template <typename InputIt,
123 typename = containers::internal::EnableIfInputIterator<InputIt>>
124 iterator insert(const_iterator pos, InputIt first, InputIt last);
125
126 iterator insert(const_iterator pos, const value_type& value) {
127 return Base::insert(pos, value);
128 }
129
130 iterator insert(const_iterator pos, value_type&& value) {
131 return Base::insert(pos, std::move(value));
132 }
133
134 iterator insert(const_iterator pos,
135 size_type count,
136 const value_type& value) {
137 return Base::insert(pos, count, value);
138 }
139
140 iterator insert(const_iterator pos, std::initializer_list<value_type> ilist) {
141 return Base::insert(pos, ilist);
142 }
143
154 [[nodiscard]] bool try_reserve(size_type new_capacity);
155
157 void reserve(size_type new_capacity) { PW_ASSERT(try_reserve(new_capacity)); }
158
168 [[nodiscard]] bool try_reserve_exact(size_type new_capacity) {
169 return new_capacity <= Base::capacity() || IncreaseCapacity(new_capacity);
170 }
171
173 void reserve_exact(size_type new_capacity) {
174 PW_ASSERT(try_reserve_exact(new_capacity));
175 }
176
180
190 void reset() {
191 Base::clear();
192 DeallocateBuffer();
193 }
194
195 constexpr size_type max_size() const noexcept {
196 return std::numeric_limits<size_type>::max();
197 }
198
200 constexpr allocator_type& get_allocator() const { return *allocator_; }
201
203 void swap(DynamicDeque& other) noexcept {
204 Base::SwapIndices(other);
205 std::swap(allocator_, other.allocator_);
206 std::swap(buffer_, other.buffer_);
207 }
208
209 private:
210 friend Base;
211
212 template <typename, typename>
213 friend class DynamicVector; // Allow direct access to data()
214
215 static constexpr bool kFixedCapacity = false; // uses dynamic allocation
216
217 // Hide full() since the capacity can grow.
218 using Base::full;
219
220 pointer data() { return std::launder(reinterpret_cast<pointer>(buffer_)); }
221 const_pointer data() const {
222 return std::launder(reinterpret_cast<const_pointer>(buffer_));
223 }
224
225 [[nodiscard]] bool IncreaseCapacity(size_type new_capacity);
226
227 size_type GetNewCapacity(const size_type new_size) {
228 // For the initial allocation, allocate at least 4 words worth of items.
229 if (Base::capacity() == 0) {
230 return std::max(size_type{4 * sizeof(void*) / sizeof(value_type)},
231 new_size);
232 }
233 // Double the capacity. May introduce other allocation policies later.
234 return std::max(mul_sat(Base::capacity(), size_type{2}), new_size);
235 }
236
237 bool ReallocateBuffer(size_type new_capacity);
238
239 void DeallocateBuffer() {
240 allocator_->Deallocate(buffer_);
241 buffer_ = nullptr;
242 Base::HandleShrunkBuffer(0);
243 }
244
245 Allocator* allocator_;
246 std::byte* buffer_; // raw array for in-place construction and destruction
247};
248
249template <typename ValueType, typename SizeType>
250DynamicDeque<ValueType, SizeType>& DynamicDeque<ValueType, SizeType>::operator=(
251 DynamicDeque&& other) noexcept {
252 Base::DestroyAll();
253 allocator_->Deallocate(buffer_);
254
255 allocator_ = other.allocator_; // The other deque keeps its allocator
256 buffer_ = std::exchange(other.buffer_, nullptr);
257
258 Base::MoveAssignIndices(other);
259 return *this;
260}
261
262template <typename ValueType, typename SizeType>
263DynamicDeque<ValueType, SizeType>::~DynamicDeque() {
264 Base::DestroyAll();
265 allocator_->Deallocate(buffer_);
266}
267
268template <typename ValueType, typename SizeType>
270 return new_capacity <= Base::capacity() ||
271 IncreaseCapacity(GetNewCapacity(new_capacity)) ||
272 IncreaseCapacity(new_capacity);
273}
274
275template <typename ValueType, typename SizeType>
277 size_type new_capacity) {
278 // Try resizing the existing array. Only works if inserting at the end.
279 if (buffer_ != nullptr && Base::CanExtendBuffer() &&
280 allocator_->Resize(buffer_, new_capacity * sizeof(value_type))) {
281 Base::HandleExtendedBuffer(new_capacity);
282 return true;
283 }
284
285 // Allocate a new array and move items to it.
286 return ReallocateBuffer(new_capacity);
287}
288
289template <typename ValueType, typename SizeType>
291 if (Base::size() == Base::capacity()) {
292 return; // Nothing to do; deque is full or buffer_ is nullptr
293 }
294
295 if (Base::empty()) { // Empty deque, but a buffer_ is allocated; free it
296 DeallocateBuffer();
297 return;
298 }
299
300 // Attempt to shrink if buffer if possible, and reallocate it if needed.
301 //
302 // If there are unused slots at the start, could shift back and Resize()
303 // instead of calling ReallocateBuffer(), but may not be worth the complexity.
304 if (Base::CanShrinkBuffer() &&
305 allocator_->Resize(buffer_, Base::size() * sizeof(value_type))) {
306 Base::HandleShrunkBuffer(Base::size());
307 } else {
308 // TODO: b/498348047 - Consider dering + resize or simply giving up.
309 ReallocateBuffer(Base::size());
310 }
311}
312
313template <typename ValueType, typename SizeType>
315 size_type new_capacity) {
316 std::byte* new_buffer = static_cast<std::byte*>(
317 allocator_->Allocate(allocator::Layout::Of<value_type[]>(new_capacity)));
318 if (new_buffer == nullptr) {
319 return false;
320 }
321
322 pointer dest = std::launder(reinterpret_cast<pointer>(new_buffer));
323 auto [data_1, data_2] = Base::contiguous_data();
324
325 if constexpr (std::is_move_constructible_v<value_type>) {
326 dest = std::uninitialized_move(data_1.begin(), data_1.end(), dest);
327 std::uninitialized_move(data_2.begin(), data_2.end(), dest);
328 } else { // if it can't be moved, try copying
329 dest = std::uninitialized_copy(data_1.begin(), data_1.end(), dest);
330 std::uninitialized_copy(data_2.begin(), data_2.end(), dest);
331 }
332
333 std::destroy(data_1.begin(), data_1.end());
334 std::destroy(data_2.begin(), data_2.end());
335
336 allocator_->Deallocate(buffer_);
337 buffer_ = new_buffer;
338
339 Base::HandleNewBuffer(new_capacity);
340 return true;
341}
342
343template <typename ValueType, typename SizeType>
344template <typename InputIt, typename>
345typename DynamicDeque<ValueType, SizeType>::iterator
346DynamicDeque<ValueType, SizeType>::insert(const_iterator pos,
347 InputIt first,
348 InputIt last) {
349 // Can't safely check std::distance for InputIterator. Use a workaround.
350 if constexpr (std::is_same_v<std::input_iterator_tag,
351 typename std::iterator_traits<
352 InputIt>::iterator_category>) {
353 // Read into a temporary deque so the items can be counted. Then, move into
354 // this deque in one operation. This way, existing items are shifted once to
355 // their final positions, instead of shifting N times for repeated inserts.
356 DynamicDeque temp(*allocator_);
357 temp.assign(first, last);
358 return Base::insert(pos,
359 std::make_move_iterator(temp.data()),
360 std::make_move_iterator(temp.data() + temp.size()));
361 } else { // Use the efficient base implementation for forward iterators.
362 return Base::insert(pos, first, last);
363 }
364}
365
366} // namespace pw
Definition: allocator.h:42
Definition: dynamic_deque.h:68
Definition: dynamic_vector.h:63
Definition: generic_deque.h:178
constexpr size_type capacity() const noexcept
Returns the maximum number of elements in the deque.
Definition: generic_deque.h:72
void Deallocate(void *ptr)
Definition: deallocator.h:59
iterator insert(const_iterator pos, const value_type &value)
Definition: generic_deque.h:351
void reserve(size_type new_capacity)
Increases capacity() to at least new_capacity. Crashes on failure.
Definition: dynamic_deque.h:157
std::optional< iterator > try_insert(const_iterator pos, const value_type &value)
Definition: generic_deque.h:469
bool try_assign(size_type count, const value_type &value)
Definition: generic_deque.h:618
void reserve_exact(size_type new_capacity)
Increases capacity() to exactly new_capacity. Crashes on failure.
Definition: dynamic_deque.h:173
constexpr DynamicDeque(DynamicDeque &&other) noexcept
Definition: dynamic_deque.h:99
std::optional< iterator > try_emplace(const_iterator pos, Args &&... args)
void swap(DynamicDeque &other) noexcept
Swaps the contents of two deques. No allocations occur.
Definition: dynamic_deque.h:203
bool try_reserve(size_type new_capacity)
Definition: dynamic_deque.h:269
void shrink_to_fit()
Definition: dynamic_deque.h:290
constexpr allocator_type & get_allocator() const
Returns the deque's allocator.
Definition: dynamic_deque.h:200
void reset()
Clears the deque and deallocates its buffer.
Definition: dynamic_deque.h:190
bool try_reserve_exact(size_type new_capacity)
Definition: dynamic_deque.h:168
constexpr DynamicDeque(Allocator &allocator) noexcept
Definition: dynamic_deque.h:90
constexpr T mul_sat(T lhs, T rhs) noexcept
Definition: saturating_arithmetic.h:75
The Pigweed namespace.
Definition: alignment.h:27