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 : Base(0), allocator_(other.allocator_), buffer_(other.buffer_) {
95 other.buffer_ = nullptr; // clear 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 // Hide full() since the capacity can grow.
197 using Base::full;
198
199 pointer data() { return std::launder(reinterpret_cast<pointer>(buffer_)); }
200 const_pointer data() const {
201 return std::launder(reinterpret_cast<const_pointer>(buffer_));
202 }
203
204 [[nodiscard]] bool IncreaseCapacity(size_type new_capacity);
205
206 size_type GetNewCapacity(const size_type new_size) {
207 // For the initial allocation, allocate at least 4 words worth of items.
208 if (Base::capacity() == 0) {
209 return std::max(size_type{4 * sizeof(void*) / sizeof(value_type)},
210 new_size);
211 }
212 // Double the capacity. May introduce other allocation policies later.
213 return std::max(mul_sat(Base::capacity(), size_type{2}), new_size);
214 }
215
216 bool ReallocateBuffer(size_type new_capacity);
217
218 Allocator* allocator_;
219 std::byte* buffer_; // raw array for in-place construction and destruction
220};
221
222template <typename ValueType, typename SizeType>
223DynamicDeque<ValueType, SizeType>& DynamicDeque<ValueType, SizeType>::operator=(
224 DynamicDeque&& other) noexcept {
225 Base::DestroyAll();
226 allocator_->Deallocate(buffer_);
227
228 allocator_ = other.allocator_; // The other deque keeps its allocator
229 buffer_ = std::exchange(other.buffer_, nullptr);
230
231 Base::MoveAssignIndices(other);
232 return *this;
233}
234
235template <typename ValueType, typename SizeType>
236DynamicDeque<ValueType, SizeType>::~DynamicDeque() {
237 Base::DestroyAll();
238 allocator_->Deallocate(buffer_);
239}
240
241template <typename ValueType, typename SizeType>
243 return new_capacity <= Base::capacity() ||
244 IncreaseCapacity(GetNewCapacity(new_capacity)) ||
245 IncreaseCapacity(new_capacity);
246}
247
248template <typename ValueType, typename SizeType>
250 size_type new_capacity) {
251 // Try resizing the existing array. Only works if inserting at the end.
252 if (buffer_ != nullptr && Base::CanExtendBuffer() &&
253 allocator_->Resize(buffer_, new_capacity * sizeof(value_type))) {
254 Base::HandleExtendedBuffer(new_capacity);
255 return true;
256 }
257
258 // Allocate a new array and move items to it.
259 return ReallocateBuffer(new_capacity);
260}
261
262template <typename ValueType, typename SizeType>
264 if (Base::size() == Base::capacity()) {
265 return; // Nothing to do; deque is full or buffer_ is nullptr
266 }
267
268 if (Base::empty()) { // Empty deque, but a buffer_ is allocated; free it
269 allocator_->Deallocate(buffer_);
270 buffer_ = nullptr;
271 Base::HandleShrunkBuffer(0);
272 return;
273 }
274
275 // Attempt to shrink if buffer if possible, and reallocate it if needed.
276 //
277 // If there are unused slots at the start, could shift back and Resize()
278 // instead of calling ReallocateBuffer(), but may not be worth the complexity.
279 if (Base::CanShrinkBuffer() &&
280 allocator_->Resize(buffer_, Base::size() * sizeof(value_type))) {
281 Base::HandleShrunkBuffer(Base::size());
282 } else {
283 ReallocateBuffer(Base::size());
284 }
285}
286
287template <typename ValueType, typename SizeType>
289 size_type new_capacity) {
290 std::byte* new_buffer = static_cast<std::byte*>(
291 allocator_->Allocate(allocator::Layout::Of<value_type[]>(new_capacity)));
292 if (new_buffer == nullptr) {
293 return false;
294 }
295
296 pointer dest = std::launder(reinterpret_cast<pointer>(new_buffer));
297 auto [data_1, data_2] = Base::contiguous_data();
298
299 if constexpr (std::is_move_constructible_v<value_type>) {
300 dest = std::uninitialized_move(data_1.begin(), data_1.end(), dest);
301 std::uninitialized_move(data_2.begin(), data_2.end(), dest);
302 } else { // if it can't be moved, try copying
303 dest = std::uninitialized_copy(data_1.begin(), data_1.end(), dest);
304 std::uninitialized_copy(data_2.begin(), data_2.end(), dest);
305 }
306
307 std::destroy(data_1.begin(), data_1.end());
308 std::destroy(data_2.begin(), data_2.end());
309
310 allocator_->Deallocate(buffer_);
311 buffer_ = new_buffer;
312
313 Base::HandleNewBuffer(new_capacity);
314 return true;
315}
316
317template <typename ValueType, typename SizeType>
318template <typename InputIt, typename>
319typename DynamicDeque<ValueType, SizeType>::iterator
320DynamicDeque<ValueType, SizeType>::insert(const_iterator pos,
321 InputIt first,
322 InputIt last) {
323 // Can't safely check std::distance for InputIterator. Use a workaround.
324 if constexpr (std::is_same_v<std::input_iterator_tag,
325 typename std::iterator_traits<
326 InputIt>::iterator_category>) {
327 // Read into a temporary deque so the items can be counted. Then, move into
328 // this deque in one operation. This way, existing items are shifted once to
329 // their final positions, instead of shifting N times for repeated inserts.
330 DynamicDeque temp(*allocator_);
331 temp.assign(first, last);
332 return Base::insert(pos,
333 std::make_move_iterator(temp.data()),
334 std::make_move_iterator(temp.data() + temp.size()));
335 } else { // Use the efficient base implementation for forward iterators.
336 return Base::insert(pos, first, last);
337 }
338}
339
340} // namespace pw
Definition: allocator.h:36
Definition: dynamic_deque.h:60
Definition: dynamic_vector.h:53
Definition: generic_deque.h:185
constexpr size_type capacity() const noexcept
Returns the maximum number of elements in the deque.
Definition: generic_deque.h:74
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:242
bool try_assign(size_type count, const value_type &value)
Definition: generic_deque.h:624
void shrink_to_fit()
Attempts to reduce capacity() to size(). Not guaranteed to succeed.
Definition: dynamic_deque.h:263
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:358
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:474
constexpr T mul_sat(T lhs, T rhs) noexcept
Definition: saturating_arithmetic.h:75
The Pigweed namespace.
Definition: alignment.h:27