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
55template <typename ValueType, typename SizeType = uint16_t>
57 : public containers::internal::
58 GenericDeque<DynamicDeque<ValueType, SizeType>, ValueType, SizeType> {
59 private:
60 using Base = containers::internal::
61 GenericDeque<DynamicDeque<ValueType, SizeType>, ValueType, SizeType>;
62
63 public:
64 using typename Base::const_iterator;
65 using typename Base::const_pointer;
66 using typename Base::const_reference;
67 using typename Base::difference_type;
68 using typename Base::iterator;
69 using typename Base::pointer;
70 using typename Base::reference;
71 using typename Base::size_type;
72 using typename Base::value_type;
73
75
80 constexpr DynamicDeque(Allocator& allocator) noexcept
81 : Base(0), allocator_(&allocator), buffer_(nullptr) {}
82
83 DynamicDeque(const DynamicDeque&) = delete;
84 DynamicDeque& operator=(const DynamicDeque&) = delete;
85
89 constexpr DynamicDeque(DynamicDeque&& other) noexcept
90 : Base(0), allocator_(other.allocator_), buffer_(other.buffer_) {
91 other.buffer_ = nullptr; // clear other's buffer_, but not its allocator_
92 Base::MoveAssignIndices(other);
93 }
94
95 DynamicDeque& operator=(DynamicDeque&& other) noexcept;
96
98
99 // Provide try_* versions of functions that return false if allocation fails.
100 using Base::try_assign;
101 using Base::try_emplace;
102 using Base::try_emplace_back;
103 using Base::try_emplace_front;
104 using Base::try_insert;
105 using Base::try_push_back;
106 using Base::try_push_front;
107 using Base::try_resize;
108
109 // The GenericDeque's input iterator insert implementation emplaces items one
110 // at a time, which is inefficient. For DynamicDeque, use a more efficient
111 // implementation that inserts all items into a temporary DynamicDeque first.
112 template <typename InputIt,
113 typename = containers::internal::EnableIfInputIterator<InputIt>>
114 iterator insert(const_iterator pos, InputIt first, InputIt last);
115
116 iterator insert(const_iterator pos, const value_type& value) {
117 return Base::insert(pos, value);
118 }
119
120 iterator insert(const_iterator pos, value_type&& value) {
121 return Base::insert(pos, std::move(value));
122 }
123
124 iterator insert(const_iterator pos,
125 size_type count,
126 const value_type& value) {
127 return Base::insert(pos, count, value);
128 }
129
130 iterator insert(const_iterator pos, std::initializer_list<value_type> ilist) {
131 return Base::insert(pos, ilist);
132 }
133
144 [[nodiscard]] bool try_reserve(size_type new_capacity);
145
147 void reserve(size_type new_capacity) { PW_ASSERT(try_reserve(new_capacity)); }
148
158 [[nodiscard]] bool try_reserve_exact(size_type new_capacity) {
159 return new_capacity <= Base::capacity() || IncreaseCapacity(new_capacity);
160 }
161
163 void reserve_exact(size_type new_capacity) {
164 PW_ASSERT(try_reserve_exact(new_capacity));
165 }
166
169
170 constexpr size_type max_size() const noexcept {
171 return std::numeric_limits<size_type>::max();
172 }
173
175 constexpr allocator_type& get_allocator() const { return *allocator_; }
176
178 void swap(DynamicDeque& other) noexcept {
179 Base::SwapIndices(other);
180 std::swap(allocator_, other.allocator_);
181 std::swap(buffer_, other.buffer_);
182 }
183
184 private:
185 friend Base;
186
187 template <typename, typename>
188 friend class DynamicVector; // Allow direct access to data()
189
190 static constexpr bool kFixedCapacity = false; // uses dynamic allocation
191
192 // Hide full() since the capacity can grow.
193 using Base::full;
194
195 pointer data() { return std::launder(reinterpret_cast<pointer>(buffer_)); }
196 const_pointer data() const {
197 return std::launder(reinterpret_cast<const_pointer>(buffer_));
198 }
199
200 [[nodiscard]] bool IncreaseCapacity(size_type new_capacity);
201
202 size_type GetNewCapacity(const size_type new_size) {
203 // For the initial allocation, allocate at least 4 words worth of items.
204 if (Base::capacity() == 0) {
205 return std::max(size_type{4 * sizeof(void*) / sizeof(value_type)},
206 new_size);
207 }
208 // Double the capacity. May introduce other allocation policies later.
209 return std::max(mul_sat(Base::capacity(), size_type{2}), new_size);
210 }
211
212 bool ReallocateBuffer(size_type new_capacity);
213
214 Allocator* allocator_;
215 std::byte* buffer_; // raw array for in-place construction and destruction
216};
217
218template <typename ValueType, typename SizeType>
219DynamicDeque<ValueType, SizeType>& DynamicDeque<ValueType, SizeType>::operator=(
220 DynamicDeque&& other) noexcept {
221 Base::DestroyAll();
222 allocator_->Deallocate(buffer_);
223
224 allocator_ = other.allocator_; // The other deque keeps its allocator
225 buffer_ = std::exchange(other.buffer_, nullptr);
226
227 Base::MoveAssignIndices(other);
228 return *this;
229}
230
231template <typename ValueType, typename SizeType>
232DynamicDeque<ValueType, SizeType>::~DynamicDeque() {
233 Base::DestroyAll();
234 allocator_->Deallocate(buffer_);
235}
236
237template <typename ValueType, typename SizeType>
239 return new_capacity <= Base::capacity() ||
240 IncreaseCapacity(GetNewCapacity(new_capacity)) ||
241 IncreaseCapacity(new_capacity);
242}
243
244template <typename ValueType, typename SizeType>
246 size_type new_capacity) {
247 // Try resizing the existing array. Only works if inserting at the end.
248 if (buffer_ != nullptr && Base::CanExtendBuffer() &&
249 allocator_->Resize(buffer_, new_capacity * sizeof(value_type))) {
250 Base::HandleExtendedBuffer(new_capacity);
251 return true;
252 }
253
254 // Allocate a new array and move items to it.
255 return ReallocateBuffer(new_capacity);
256}
257
258template <typename ValueType, typename SizeType>
260 if (Base::size() == Base::capacity()) {
261 return; // Nothing to do; deque is full or buffer_ is nullptr
262 }
263
264 if (Base::empty()) { // Empty deque, but a buffer_ is allocated; free it
265 allocator_->Deallocate(buffer_);
266 buffer_ = nullptr;
267 Base::HandleShrunkBuffer(0);
268 return;
269 }
270
271 // Attempt to shrink if buffer if possible, and reallocate it if needed.
272 //
273 // If there are unused slots at the start, could shift back and Resize()
274 // instead of calling ReallocateBuffer(), but may not be worth the complexity.
275 if (Base::CanShrinkBuffer() &&
276 allocator_->Resize(buffer_, Base::size() * sizeof(value_type))) {
277 Base::HandleShrunkBuffer(Base::size());
278 } else {
279 ReallocateBuffer(Base::size());
280 }
281}
282
283template <typename ValueType, typename SizeType>
285 size_type new_capacity) {
286 std::byte* new_buffer = static_cast<std::byte*>(
287 allocator_->Allocate(allocator::Layout::Of<value_type[]>(new_capacity)));
288 if (new_buffer == nullptr) {
289 return false;
290 }
291
292 pointer dest = std::launder(reinterpret_cast<pointer>(new_buffer));
293 auto [data_1, data_2] = Base::contiguous_data();
294
295 if constexpr (std::is_move_constructible_v<value_type>) {
296 dest = std::uninitialized_move(data_1.begin(), data_1.end(), dest);
297 std::uninitialized_move(data_2.begin(), data_2.end(), dest);
298 } else { // if it can't be moved, try copying
299 dest = std::uninitialized_copy(data_1.begin(), data_1.end(), dest);
300 std::uninitialized_copy(data_2.begin(), data_2.end(), dest);
301 }
302
303 std::destroy(data_1.begin(), data_1.end());
304 std::destroy(data_2.begin(), data_2.end());
305
306 allocator_->Deallocate(buffer_);
307 buffer_ = new_buffer;
308
309 Base::HandleNewBuffer(new_capacity);
310 return true;
311}
312
313template <typename ValueType, typename SizeType>
314template <typename InputIt, typename>
315typename DynamicDeque<ValueType, SizeType>::iterator
316DynamicDeque<ValueType, SizeType>::insert(const_iterator pos,
317 InputIt first,
318 InputIt last) {
319 // Can't safely check std::distance for InputIterator. Use a workaround.
320 if constexpr (std::is_same_v<std::input_iterator_tag,
321 typename std::iterator_traits<
322 InputIt>::iterator_category>) {
323 // Read into a temporary deque so the items can be counted. Then, move into
324 // this deque in one operation. This way, existing items are shifted once to
325 // their final positions, instead of shifting N times for repeated inserts.
326 DynamicDeque temp(*allocator_);
327 temp.assign(first, last);
328 return Base::insert(pos,
329 std::make_move_iterator(temp.data()),
330 std::make_move_iterator(temp.data() + temp.size()));
331 } else { // Use the efficient base implementation for forward iterators.
332 return Base::insert(pos, first, last);
333 }
334}
335
336} // namespace pw
Definition: allocator.h:45
Definition: dynamic_deque.h:58
Definition: dynamic_vector.h:53
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
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:147
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:163
constexpr DynamicDeque(DynamicDeque &&other) noexcept
Definition: dynamic_deque.h:89
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:178
bool try_reserve(size_type new_capacity)
Definition: dynamic_deque.h:238
void shrink_to_fit()
Attempts to reduce capacity() to size(). Not guaranteed to succeed.
Definition: dynamic_deque.h:259
constexpr allocator_type & get_allocator() const
Returns the deque's allocator.
Definition: dynamic_deque.h:175
bool try_reserve_exact(size_type new_capacity)
Definition: dynamic_deque.h:158
constexpr DynamicDeque(Allocator &allocator) noexcept
Definition: dynamic_deque.h:80
constexpr T mul_sat(T lhs, T rhs) noexcept
Definition: saturating_arithmetic.h:75
The Pigweed namespace.
Definition: alignment.h:27