SuperDex Physics C++ API
Loading...
Searching...
No Matches
dynamic_array.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
22
23#if MOCHI_LANGUAGE_CPP20
24#include <concepts>
25#endif
26#include <algorithm>
27#include <cstddef>
28#include <iterator>
29#include <limits>
30#include <tuple>
31#include <type_traits>
32#include <utility>
33
34namespace superdex {
35
36// Define MOCHI_DARRAY_DEBUG to 1 to enable safety checks in DynamicArray
37#ifndef MOCHI_DARRAY_DEBUG
38#define MOCHI_DARRAY_DEBUG MOCHI_DEBUG
39#endif
40
41#if MOCHI_DARRAY_DEBUG && MOCHI_ASSERT_ENABLED
42#define MOCHI_DARRAY_ASSERT(cond, ...) MOCHI_ASSERT(cond, __VA_ARGS__)
43#else
44#define MOCHI_DARRAY_ASSERT(cond, ...)
45#endif
46
47#if MOCHI_LANGUAGE_CPP20
48// Only until the Unreal Engine Android toolchain gets an updated compiler that supports the
49// std::forward_iterator concept.
50template <class From, class To>
52 std::is_convertible_v<From, To> && requires { static_cast<To>(std::declval<From>()); };
53template <typename T>
54concept HasDistance = requires(T t) {
55 { std::distance(t, t) } -> ConvertibleTo<std::ptrdiff_t>;
56};
57#define MOCHI_DARRAY_ASSERT_FORWARD_ITERATOR(IteratorType) \
58 static_assert( \
59 HasDistance<IteratorType>, \
60 "This type of input iterator is not supported by DynamicArray because there is no way to " \
61 "reserve sufficient memory up front. We would have to loop calling emplace_back, which " \
62 "would be inefficient. Consider initializing this DynamicArray in a different way.");
63#else
64#define MOCHI_DARRAY_ASSERT_FORWARD_ITERATOR(IteratorType) \
65 static_assert( \
66 std::is_base_of_v< \
67 std::forward_iterator_tag, \
68 typename std::iterator_traits<IteratorType>::iterator_category>, \
69 "This type of input iterator is not supported by DynamicArray because there is no way to " \
70 "reserve sufficient memory up front. We would have to loop calling emplace_back, which " \
71 "would be inefficient. Consider initializing this DynamicArray in a different way.");
72#endif
73
74/** @brief Trait to determine if a type is safe for use with @ref DynamicArray::resize_noinit. */
75template <typename T>
76struct IsResizeNoInitSafe : std::bool_constant<std::is_trivially_copyable_v<T>> {};
77
78/** @brief Helper variable template for @ref IsResizeNoInitSafe. */
79template <typename T>
81
82/**
83 * @brief A dynamically resizable array with syntax and behavior similar to std::pmr::vector
84 *
85 * @remarks
86 * - Optionally provide your own polymorphic allocator.
87 * - Compatible with FILO allocators as long as you reserve or resize sufficient memory.
88 * - Extends the std::pmr::vector syntax with new methods including resize_noinit and append.
89 *
90 * @warning DynamicArray does not provide equivalent exception safety guarantees as std::vector.
91 * Exception-safe use assumes that element construction, assignment, destruction, move operations,
92 * and allocator operations do not throw. For example:
93 * - Reallocation via emplace_back, push_back, append, assign, reserve, resize, or shrink_to_fit
94 * can leak memory or leave the array in an invalid state if T's move constructor throws.
95 * - Construction, append, assign, and resize can leak memory or leave the array in an invalid
96 * state if T's constructors or assignment operators throw.
97 * - Moving from a DynamicArray with a different allocator does not provide the same rollback or
98 * cleanup guarantees as std::vector if moving elements throws.
99 * - Allocator exceptions may leave the array in an invalid state in code paths that release old
100 * storage before allocating new storage.
101 *
102 * @tparam T Element value type.
103 */
104template <class T>
106 public:
107 static_assert(
108 !std::is_same_v<T, Allocator> && !std::is_same_v<T, Allocator*>,
109 "DynamicArray of allocators is not allowed because of overload ambiguity.");
110
111 using const_iterator = T const*;
112 using iterator = T*;
113 using value_type = T;
114 using size_type = size_t;
115
116 /**
117 * @brief Construct an empty DynamicArray with the default allocator.
118 */
119 DynamicArray() = default;
120
121 /**
122 * @brief Construct an empty DynamicArray with a specific allocator.
123 *
124 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
125 */
126 explicit DynamicArray(Allocator* allocator) : _allocator(allocator) {}
127
128 /**
129 * @brief Construct a DynamicArray with an initial size. All elements will be default constructed
130 * or zero-initialized (for POD types).
131 *
132 * @param size Initial size (number of elements, not bytes)
133 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
134 */
136 : _allocator(allocator) {
137 if (size > 0) {
138 _begin = static_cast<T*>(allocator->allocate(size * sizeof(T), alignof(T)));
139 _end = _endCapacity = _begin + size;
140 DefaultConstructRange(_begin, _end);
141 }
142 }
143
144 /**
145 * @brief Construct a DynamicArray filled with copies of the specified value.
146 *
147 * @tparam FromT Input value type. Must be same or convertible to type T.
148 * @param size Initial size (number of elements, not bytes)
149 * @param defaultValue Value to copy to all new array elements.
150 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
151 */
152 template <typename FromT, MOCHI_CONCEPT((std::is_convertible_v<FromT, T>))>
155 FromT const& defaultValue,
156 Allocator* allocator = GetDefaultAllocator())
157 : _allocator(allocator) {
158 if (size > 0) {
159 _begin = static_cast<T*>(allocator->allocate(size * sizeof(T), alignof(T)));
160 _end = _endCapacity = _begin + size;
161 CopyConstructRangeFromValue(_begin, _end, defaultValue);
162 }
163 }
164
165 /**
166 * @brief Construct a DynamicArray and copy values from the half-open range:
167 * [rangeBegin, rangeEnd)
168 *
169 * @tparam InputIt Input forward iterator type (typically deduced).
170 * @param rangeBegin Iterator pointing to the first input value to copy.
171 * @param rangeEnd Iterator pointing ONE PAST the last input value to copy.
172 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
173 */
174 template <
175 typename InputIt,
176 MOCHI_CONCEPT((std::is_base_of_v<
177 std::input_iterator_tag,
178 typename std::iterator_traits<InputIt>::iterator_category>))>
179 DynamicArray(InputIt rangeBegin, InputIt rangeEnd, Allocator* allocator = GetDefaultAllocator())
180 : _allocator(allocator) {
182 auto size = static_cast<size_type>(std::distance(rangeBegin, rangeEnd));
183 if (size > 0) {
184 _begin = static_cast<T*>(allocator->allocate(size * sizeof(T), alignof(T)));
185 _end = _endCapacity = _begin + size;
186 CopyConstructRange(_begin, rangeBegin, rangeEnd);
187 }
188 }
189
190 /**
191 * @brief Construct a DynamicArray and copy values from a std::initializer_list.
192 *
193 * @param list List from which values will be copied.
194 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
195 */
196 DynamicArray(std::initializer_list<T> const& list, Allocator* allocator = GetDefaultAllocator())
197 : DynamicArray(std::begin(list), std::end(list), allocator) {}
198
199 /**
200 * @brief Construct a DynamicArray and copy values from another iterable container type like
201 * superdex::Span, std::vector, std::list, etc...
202 *
203 * @tparam InputContainerT Input container type. Must support std::begin and std::end.
204 * @param other Container from which values will be copied.
205 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
206 */
207 template <
208 typename InputContainerT,
210 (!std::is_same_v<std::decay_t<InputContainerT>, DynamicArray> &&
211 sizeof(decltype(std::begin(std::declval<InputContainerT const&>()))) &&
212 sizeof(decltype(std::end(std::declval<InputContainerT const&>())))))>
213 explicit DynamicArray(InputContainerT const& other, Allocator* allocator = GetDefaultAllocator())
214 : DynamicArray(std::begin(other), std::end(other), allocator) {}
215
216 /**
217 * @brief Construct a DynamicArray and copy values from another one.
218 *
219 * @param other Another DynamicArray from which values will be copied.
220 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
221 */
222 DynamicArray(DynamicArray const& other, Allocator* allocator)
223 : DynamicArray(other.begin(), other.end(), allocator) {}
224
225 /**
226 * @brief Copy construct from another DynamicArray. Use the same allocator.
227 *
228 * @param other Another DynamicArray from which the allocator and the values will be copied.
229 */
231 : DynamicArray(other.begin(), other.end(), other._allocator) {}
232
233 /**
234 * @brief Construct a DynamicArray by moving memory or values from another one.
235 *
236 * @remarks If the allocators are equal, then array memory ownership will be transferred from
237 * the other array to this one. Otherwise, new memory will be allocated for this array (if
238 * necessary) and then the other array's values will be moved into it. Either way, the other
239 * array will be empty after this call.
240 *
241 * @param other Another DynamicArray from which memory or values will be moved
242 * @param allocator Pointer to a polymorphic allocator. Must outlive this DynamicArray object.
243 */
244 DynamicArray(DynamicArray&& other, Allocator* allocator) : _allocator(allocator) {
245 if (other._allocator->is_equal(*_allocator)) MOCHI_LIKELY {
246 _begin = other._begin;
247 _end = other._end;
248 _endCapacity = other._endCapacity;
249 other._begin = other._end = other._endCapacity = nullptr;
250 } else if (!other.empty()) {
251 auto size = other.size();
252 _begin = static_cast<T*>(_allocator->allocate(size * sizeof(T), alignof(T)));
253 _end = _begin;
254 _endCapacity = _begin + size;
255 // Move construct each element individually, advancing _end after each successful
256 // construction.
257 for (auto src = other._begin; src < other._end; ++src, ++_end) {
258 new (_end) T(std::move(*src)); // Move construct
259 }
260 other.clear();
261 }
262 }
263
264 /**
265 * @brief Move construct from another DynamicArray. Use the same allocator.
266 * @remarks Memory ownership is always transferred. No new allocation.
267 *
268 * @param other Another DynamicArray from which memory will be moved. Will be empty after this
269 * call.
270 */
271 DynamicArray(DynamicArray&& other) noexcept
272 : _begin(other._begin),
273 _end(other._end),
274 _endCapacity(other._endCapacity),
275 _allocator(other._allocator) {
276 other._begin = other._end = other._endCapacity = nullptr;
277 }
278
279 /**
280 * @brief Destroy the DynamicArray object and all of its elements. Deallocate any memory that
281 * was used.
282 */
284 if (_begin != nullptr) {
285 DestroyRange(_begin, _end);
286 _allocator->deallocate(_begin, capacity() * sizeof(T), alignof(T));
287#if MOCHI_DARRAY_DEBUG
288 _begin = _end = _endCapacity = nullptr;
289 _allocator = nullptr;
290#endif // MOCHI_DARRAY_DEBUG
291 }
292 }
293
294 /**
295 * @brief Get an iterator pointing to the beginning of the array.
296 */
298 return _begin;
299 }
300
301 /**
302 * @brief Get a const iterator pointing to the beginning of the array.
303 */
305 return _begin;
306 }
307
308 /**
309 * @brief Get a const iterator pointing to the beginning of the array.
310 */
312 return _begin;
313 }
314
315 /**
316 * @brief Get an iterator pointing to the next element AFTER the end of the array.
317 */
319 return _end;
320 }
321
322 /**
323 * @brief Get a const iterator pointing to the next element AFTER the end of the array.
324 */
325 [[nodiscard]] MOCHI_FORCE_INLINE const_iterator end() const {
326 return _end;
327 }
328
329 /**
330 * @brief Get a const iterator pointing to the next element AFTER the end of the array.
331 */
332 [[nodiscard]] MOCHI_FORCE_INLINE const_iterator cend() const {
333 return _end;
334 }
335
336 /**
337 * @brief Get a reference to the first element. Array must not be empty.
338 */
339 [[nodiscard]] MOCHI_FORCE_INLINE T& front() {
340 MOCHI_DARRAY_ASSERT(!empty(), "Cannot get front of empty array");
341 return *_begin;
342 }
343
344 /**
345 * @brief Get a const reference to the first element. Array must not be empty.
346 */
347 [[nodiscard]] MOCHI_FORCE_INLINE T const& front() const {
348 MOCHI_DARRAY_ASSERT(!empty(), "Cannot get front of empty array");
349 return *_begin;
350 }
351
352 /**
353 * @brief Get a reference to the last element. Array must not be empty.
354 */
355 [[nodiscard]] MOCHI_FORCE_INLINE T& back() {
356 MOCHI_DARRAY_ASSERT(!empty(), "Cannot get back of empty array");
357 return *(_end - 1);
358 }
359
360 /**
361 * @brief Get a const reference to the last element. Array must not be empty.
362 */
363 [[nodiscard]] MOCHI_FORCE_INLINE T const& back() const {
364 MOCHI_DARRAY_ASSERT(!empty(), "Cannot get back of empty array");
365 return *(_end - 1);
366 }
367
368 /**
369 * @brief Get a pointer to the first element. May be nullptr if this array is empty.
370 */
371 [[nodiscard]] MOCHI_FORCE_INLINE T* data() {
372 return _begin;
373 }
374
375 /**
376 * @brief Get a const pointer to the first element. May be nullptr if this array is empty.
377 */
378 [[nodiscard]] MOCHI_FORCE_INLINE T const* data() const {
379 return _begin;
380 }
381
382 /**
383 * @brief Get the number of elements in the array.
384 */
385 [[nodiscard]] MOCHI_FORCE_INLINE size_type size() const {
386 return _end - _begin;
387 }
388
389 /**
390 * @brief Get the number of elements that could fit in the array without allocating more memory.
391 */
392 [[nodiscard]] MOCHI_FORCE_INLINE size_type capacity() const {
393 return _endCapacity - _begin;
394 }
395
396 /**
397 * @brief Return true if the array is empty (zero size).
398 */
399 [[nodiscard]] MOCHI_FORCE_INLINE bool empty() const {
400 return _end == _begin;
401 }
402
403 /**
404 * @brief Set the size. If larger than the current size, new elements will be default constructed
405 * (zero-initialized for POD types).
406 *
407 * @param newSize New number of elements
408 *
409 * @remarks The first time you call resize, capacity will be allocated for the exact size
410 * requested. However, subsequent calls to resize may allocate more than requested, similar to
411 * emplace_back.
412 */
413 void resize(size_type newSize) {
414 if (newSize > size()) {
415 if (newSize > capacity()) {
416 GrowCapacity(_begin ? GetNextCapacity(newSize) : newSize);
417 }
418 DefaultConstructRange(_end, _begin + newSize);
419 } else {
420 DestroyRange(_begin + newSize, _end);
421 }
422 _end = _begin + newSize;
423 }
424
425 /**
426 * @brief Set the size. If larger than the current size, new elements will be copy constructed
427 * from the given value.
428 *
429 * @param newSize New number of elements
430 * @param value Value to copy to new elements (if any).
431 *
432 * @warning The value parameter is not allowed to be a reference to an element within this
433 * same DynamicArray. In that case, consider using a copy of the value instead.
434 *
435 * @remarks The first time you call resize, capacity will be allocated for the exact size
436 * requested. However, subsequent calls to resize may allocate more than requested, similar to
437 * emplace_back.
438 */
439 void resize(size_type newSize, T const& value) {
440 if (newSize > size()) {
441 if (newSize > capacity()) {
442 GrowCapacity(_begin ? GetNextCapacity(newSize) : newSize);
443 }
444 CopyConstructRangeFromValue(_end, _begin + newSize, value);
445 } else {
446 DestroyRange(_begin + newSize, _end);
447 }
448 _end = _begin + newSize;
449 }
450
451 /**
452 * @brief Set the size but do not initialize any new elements. They will be in an undefined state!
453 *
454 * @param newSize New number of elements
455 *
456 * @warning This method may be used as an optimization, but only if you can guarantee that any new
457 * elements will be initialized before being used.
458 *
459 * @note Only supported for types satisfying @ref kIsResizeNoInitSafe.
460 * @note The first time you call resize_noinit, capacity will be allocated for the exact size
461 * requested. However, subsequent calls to resize_noinit may allocate more than requested, similar
462 * to emplace_back.
463 */
464 void resize_noinit(size_type newSize) {
465 static_assert(
466 kIsResizeNoInitSafe<T>, "DynamicArray::resize_noinit is not supported for this type");
467 size_type prevSize = size();
468 if (newSize > prevSize) {
469 if (newSize > capacity()) {
470 GrowCapacity(_begin ? GetNextCapacity(newSize) : newSize);
471 }
472 _end = _begin + newSize;
473 DebugFillWithNaN(_begin + prevSize, _end);
474 } else {
475 DestroyRange(_begin + newSize, _end);
476 _end = _begin + newSize;
477 }
478 }
479
480 /**
481 * @brief Reset the state of this DynamicArray using the arguments from any constructor. Any
482 * previous elements will be destroyed. Any previous memory will be deallocated.
483 *
484 * @remarks This method can be used to assign a new allocator pointer to a DynamicArray object
485 * that has already been constructed (unlike move assignment, which does not move the allocator).
486 *
487 * @tparam Args Any argument types supported by one of the DynamicArray constructors.
488 * @param args Any parameter types supported by one of the DynamicArray constructors.
489 */
490 template <typename... Args>
491 void reset(Args&&... args) {
492 this->~DynamicArray<T>();
493 new (this) DynamicArray<T>(std::forward<Args>(args)...);
494 }
495
496 /**
497 * @brief Ensure that this array has at least the specified capacity.
498 *
499 * @param newCapacity Desired capacity measured by number of elements (not bytes).
500 *
501 * @warning If you call reserve repeatedly with incrementally larger values, it will reallocate
502 * the memory every time. It will not overallocate the memory the way emplace_back does.
503 */
504 void reserve(size_type newCapacity) {
505 if (newCapacity > capacity()) {
506 GrowCapacity(newCapacity);
507 }
508 }
509
510 /**
511 * @brief Set the size to zero. Does not deallocate memory.
512 * @see shrink_to_fit
513 */
514 void clear() {
515 DestroyRange(_begin, _end);
516 _end = _begin;
517 }
518
519 /**
520 * @brief Ensure that the capacity (memory allocated) is no larger than the size (memory used).
521 */
523 if (_endCapacity > _end) {
524 if (empty()) {
525 _allocator->deallocate(_begin, capacity() * sizeof(T), alignof(T));
526 _begin = _end = _endCapacity = nullptr;
527 } else {
528 auto const n = size();
529 auto* newBegin = static_cast<T*>(_allocator->allocate(n * sizeof(T), alignof(T)));
530 MoveConstructRange(newBegin, _begin, n);
531 DestroyRange(_begin, _end);
532 _allocator->deallocate(_begin, capacity() * sizeof(T), alignof(T));
533 _begin = newBegin;
534 _end = _endCapacity = newBegin + n;
535 }
536 }
537 }
538
539 /**
540 * @brief Emplace a new element at the end of the array.
541 *
542 * @remarks If people use reserve or resize, then we will allocate the exact capacity requested.
543 * However, if people call push_back or emplace_back repeatedly, we will grow the capacity by 50%
544 * each time more memory is needed. This achieves amortized O(1) cost, similar to std::vector.
545 *
546 * Unlike std::vector, we skip past the first few reallocations by reserving a capacity of
547 * kGrowthPatternStartSize the first time. See GetNextCapacity() for details.
548 *
549 * @warning The argument is not allowed to be a reference to an element within this same
550 * DynamicArray. In that case, consider emplacing a copy of the element instead.
551 *
552 * @tparam Args Any types that can be passed to type T's constructor.
553 * @param args Any arguments that can be passed to type T's constructor.
554 */
555 template <class... Args>
556 void emplace_back(Args&&... args) {
557 if constexpr (sizeof...(Args) == 1) {
558 if constexpr (std::is_same_v<
559 T,
560 std::remove_cv_t<std::remove_reference_t<decltype(std::get<0>(
561 std::forward_as_tuple(args...)))>>>) {
563 !IsInThisArray(&std::get<0>(std::forward_as_tuple(args...))),
564 "You are not allowed to push an element of a DynamicArray onto the end of the same DynamicArray. "
565 "Consider pushing a copy of the value instead.");
566 }
567 }
568 if (_endCapacity == _end) MOCHI_UNLIKELY {
569 GrowCapacity(GetNextCapacity(size() + 1));
570 }
571 new (_end) T(std::forward<Args>(args)...);
572 ++_end;
573 }
574
575 /**
576 * @brief Copy the value to a new element at the end of the array.
577 *
578 * @remarks May over allocate to achieve amortized O(1) cost like emplace_back.
579 *
580 * @warning The argument is not allowed to be a reference to an element within this same
581 * DynamicArray. In that case, consider pushing a copy of the element instead.
582 *
583 * @param value Value to be copied
584 * @see emplace_back
585 */
586 MOCHI_FORCE_INLINE void push_back(T const& value) {
587 emplace_back(value); // emplace via copy constructor
588 }
589
590 /**
591 * @brief Move the value to a new element at the end of the array.
592 *
593 * @remarks May over allocate to achieve amortized O(1) cost like emplace_back.
594 *
595 * @warning The argument is not allowed to be a reference to an element within this same
596 * DynamicArray. In that case, consider pushing a copy of the element instead.
597 *
598 * @param value Value to be moved
599 * @see emplace_back
600 */
601 void push_back(T&& value) {
602 emplace_back(std::move(value)); // emplace via move constructor
603 }
604
605 /**
606 * @brief Default construct a new element at the end of the array.
607 * @remarks May over allocate to achieve amortized O(1) cost like emplace_back.
608 *
609 * @code{.cpp}
610 * auto& obj = myArray.push_back();
611 * obj.value = someValue;
612 * @endcode
613 *
614 * @return T& A reference to the new element
615 */
617 emplace_back();
618 return back();
619 }
620
621 /**
622 * @brief Remove the last element of the array (must not be empty).
623 */
624 void pop_back() {
625 MOCHI_DARRAY_ASSERT(!empty(), "Cannot pop_back an empty array");
626 --_end;
627 if constexpr (!std::is_trivially_destructible_v<T>) {
628 _end->~T();
629 }
630 }
631
632 /**
633 * @brief Remove the half-open range [rangeBegin, rangeEnd) from this array. Any later elements
634 * will be shifted down to preserve order.
635 *
636 * @remarks Size will be reduced by (rangeEnd - rangeBegin).
637 *
638 * @param rangeBegin_ Iterator pointing to the first element to remove.
639 * @param rangeEnd_ Iterator pointing ONE PAST the last element to remove.
640 */
641 void erase(const_iterator rangeBegin_, const_iterator rangeEnd_) {
642 // Const cast so we don't have to implement both erase(iterator, iterator) and
643 // erase(const_iterator, const_iterator).
644 auto rangeBegin = const_cast<iterator>(rangeBegin_);
645 auto rangeEnd = const_cast<iterator>(rangeEnd_);
646 if (rangeEnd == _end) {
647 MOCHI_DARRAY_ASSERT(rangeBegin >= _begin && rangeBegin <= _end, "Invalid iterator");
648 // Erase from the end. This is the most common case.
649 DestroyRange(rangeBegin, rangeEnd);
650 _end = rangeBegin;
651 } else if (rangeEnd != rangeBegin) {
652 MOCHI_DARRAY_ASSERT(rangeBegin <= rangeEnd, "Invalid iterator range");
653 MOCHI_DARRAY_ASSERT(IsInThisArray(rangeBegin, rangeEnd), "Invalid iterator");
654 // Erase from the middle and shift elements down
655 if constexpr (std::is_trivially_move_assignable_v<T>) {
656 memmove(rangeBegin, rangeEnd, (_end - rangeEnd) * sizeof(T));
657 } else {
658 T* dst = rangeBegin;
659 T* src = const_cast<T*>(rangeEnd); // First value to move, after the range to erase
660 for (; src != _end; ++dst, ++src) {
661 *dst = std::move(*src); // Move assignment
662 }
663 }
664 auto numRemoved = (rangeEnd - rangeBegin);
665 auto newSize = size() - numRemoved;
666 DestroyRange(_begin + newSize, _end);
667 _end = _begin + newSize;
668 }
669 }
670
671 /**
672 * @brief Remove one element from this array. Any later elements will be shifted down to preserve
673 * order.
674 *
675 * @param it_ Iterator pointing to the element to remove.
676 */
678 // Const cast so we don't have to implement both erase(iterator) and erase(const_iterator).
679 auto it = const_cast<iterator>(it_);
680 MOCHI_DARRAY_ASSERT(it >= _begin && it < _end, "Invalid iterator");
681 if (it + 1 == _end) {
682 // Erase from the end. This is the most common case.
683 Destroy(it);
684 _end = it;
685 } else {
686 erase(it, it + 1);
687 }
688 }
689
690 /**
691 * @brief Remove one element from this array and swap the last element into its place. This
692 * achieves O(1) cost but does not preserve order.
693 *
694 * @param it Iterator pointing to the element to remove.
695 */
697 MOCHI_DARRAY_ASSERT(it >= _begin && it < _end, "Invalid iterator");
698 auto* last = _end - 1;
699 if (it != last) {
700 *it = std::move(*last);
701 }
702 Destroy(last);
703 _end = last;
704 }
705
706 /**
707 * @brief Replace the contents of this DynamicArray by copying values from the half-open range
708 * [rangeBegin, rangeEnd).
709 *
710 * @warning The iterators are not allowed to point to elements within this same DynamicArray.
711 *
712 * @tparam InputIt Input iterator type (typically deduced).
713 * @param rangeBegin Iterator pointing to the first value to copy from.
714 * @param rangeEnd Iterator pointing ONE PAST the last value to copy from.
715 */
716 template <
717 typename InputIt,
718 MOCHI_CONCEPT((std::is_base_of_v<
719 std::input_iterator_tag,
720 typename std::iterator_traits<InputIt>::iterator_category>))>
721 void assign(InputIt rangeBegin, InputIt rangeEnd) {
723 if constexpr (std::is_pointer_v<InputIt>) {
724 MOCHI_DARRAY_ASSERT(rangeBegin <= rangeEnd, "Invalid input range");
726 !IsInThisArray(rangeBegin, rangeEnd),
727 "The input range is not allowed to point to memory within the DynamicArray that is being modified.");
728 }
729 auto const oldSize = size();
730 auto const newSize = static_cast<size_type>(std::distance(rangeBegin, rangeEnd));
732 _allocator || (newSize == oldSize),
733 "It is illegal to change the size of a DynamicArray that does not own the memory.");
734 if (newSize <= oldSize) {
735 // This array is getting smaller
736 _end = _begin + newSize;
737 DestroyRange(_begin + newSize, _begin + oldSize);
738 std::copy(rangeBegin, rangeEnd, _begin);
739 } else if (newSize <= capacity()) {
740 // This array is getting larger. Sufficient capacity exists.
741 _end += (newSize - oldSize);
742 if constexpr (std::is_trivially_copyable_v<T>) {
743 // We can copy the full range without worrying about a user-defined constructor or
744 // assignment operator.
745 std::copy(rangeBegin, rangeEnd, _begin);
746 } else {
747 // Copy assign existing values
748 auto src = rangeBegin;
749 std::copy_n(src, oldSize, _begin);
750 // Copy construct new values
751 std::advance(src, oldSize);
752 for (size_type i = oldSize; i < newSize; ++i, ++src) {
753 new (_begin + i) T(*src);
754 }
755 }
756 } else {
757 // This array is getting larger and needs to allocate new capacity
758 if constexpr (
759 std::is_trivially_copyable_v<T> && std::is_trivially_move_constructible_v<T> &&
760 std::is_trivially_move_assignable_v<T> && std::is_trivially_destructible_v<T>) {
761 // We can deallocate the old memory before allocating the new memory because we don't need
762 // to read nor destruct the old values. We can simply copy the full range to the new
763 // memory location.
764 if (_begin) {
765 _allocator->deallocate(_begin, capacity() * sizeof(T), alignof(T));
766 }
767 _begin = static_cast<T*>(_allocator->allocate(newSize * sizeof(T), alignof(T)));
768 _end = _endCapacity = _begin + newSize;
769 std::copy(rangeBegin, rangeEnd, _begin);
770 } else {
771 // Allocate memory and move existing values.
772 GrowCapacity(newSize); // exact capacity
773 _end = _begin + newSize;
774 // Copy assign over existing values
775 auto src = rangeBegin;
776 std::copy_n(src, oldSize, _begin);
777 // Copy construct new values
778 std::advance(src, oldSize);
779 CopyConstructRange(_begin + oldSize, src, rangeEnd);
780 }
781 }
782 }
783
784 /**
785 * @brief Add values to the end of this DynamicArray by copying them from the half-open range
786 * [rangeBegin, rangeEnd).
787 *
788 * @warning The iterators are not allowed to point to elements within this same DynamicArray.
789 * Consider appending a copy of the elements instead.
790 *
791 * @tparam InputIt Input iterator type (typically deduced).
792 * @param rangeBegin Iterator pointing to the first input value to copy.
793 * @param rangeEnd Iterator pointing ONE PAST the last input value to copy.
794 */
795 template <class InputIt>
796 void append(InputIt rangeBegin, InputIt rangeEnd) {
799 !IsInThisArray(rangeBegin, rangeEnd),
800 "The input range is not allowed to point to memory within the DynamicArray that is being modified.");
801 auto count = std::distance(rangeBegin, rangeEnd);
802 MOCHI_DARRAY_ASSERT(count >= 0, "Invalid input range");
803 auto prevSize = size();
804 auto newSize = prevSize + count;
805 if (newSize > capacity()) MOCHI_UNLIKELY {
806 GrowCapacity(GetNextCapacity(newSize));
807 }
808 _end = _begin + newSize;
809 CopyConstructRange(_begin + prevSize, rangeBegin, rangeEnd);
810 }
811
812 /**
813 * @brief Add values to the end of this DynamicArray by copying them from another iterable
814 * container.
815 *
816 * @warning It is illegal to append a DynamicArray to itself.
817 *
818 * @tparam InputContainerT Another iterable container type. Must support std::begin and
819 * std::end.
820 * @param container Container from which value will be copied.
821 */
822 template <class InputContainerT>
823 MOCHI_FORCE_INLINE void append(InputContainerT const& container) {
824 append(std::begin(container), std::end(container));
825 }
826
827 /**
828 * @brief Get a pointer to the polymorphic allocator.
829 */
831 return _allocator;
832 }
833
834 /**
835 * @brief Get a reference to the value at index i.
836 */
838 MOCHI_DARRAY_ASSERT(i < size(), "Index out of range");
839 return _begin[i];
840 }
841
842 /**
843 * @brief Get a reference to the value at index i.
844 */
845 [[nodiscard]] MOCHI_FORCE_INLINE T const& operator[](size_type i) const {
846 MOCHI_DARRAY_ASSERT(i < size(), "Index out of range");
847 return _begin[i];
848 }
849
850 /**
851 * @brief Copy Assignment: Replace the contents of this DynamicArray by copying values from
852 * another one.
853 *
854 * @param other Another DynamicArray from which values will be copied.
855 * @return *this
856 */
858 if (&other != this) MOCHI_LIKELY {
859 assign(other.begin(), other.end());
860 }
861 return *this;
862 }
863
864 /**
865 * @brief Move Assignment: Replace the contents of this DynamicArray by moving memory or values
866 * from another one.
867 *
868 * @remarks If the allocators are equal, then array memory ownership will be transferred from
869 * the other array to this one. Otherwise, new memory will be allocated for this array (if
870 * necessary) and then the other array's values will be moved into it. Either way, the other
871 * array will be empty after this call.
872 *
873 * @param other Another DynamicArray from which memory or values will be moved.
874 * @return *this
875 */
877 if (&other != this) MOCHI_LIKELY {
878 clear();
879 if (_allocator->is_equal(*other._allocator)) MOCHI_LIKELY {
880 // Release any previously allocated memory
881 if (_begin != nullptr) {
882 _allocator->deallocate(_begin, capacity() * sizeof(T), alignof(T));
883 }
884 // Move ownership of the other memory to this array
885 _begin = other._begin;
886 _end = other._end;
887 _endCapacity = other._endCapacity;
888 other._begin = other._end = other._endCapacity = nullptr;
889 } else if (!other.empty()) {
890 // Ensure sufficient capacity using our allocator
891 auto const newSize = other.size();
892 if (newSize > capacity()) {
893 GrowCapacity(newSize);
894 }
895 // Move construct each element individually, advancing _end after each successful
896 // construction. If T's move constructor throws, the destructor will only destroy elements
897 // that were successfully constructed.
898 for (auto src = other._begin; src < other._end; ++src, ++_end) {
899 new (_end) T(std::move(*src)); // Move construct
900 }
901 // Destroy the elements in the rhs array, which have already been moved.
902 // No need to release memory in the rhs array at this time.
903 other.clear();
904 }
905 }
906 return *this;
907 }
908
909 /**
910 * @brief Copy Assignment: Replace the contents of this DynamicArray by copying values from
911 * a std::initializer_list.
912 *
913 * @param list List of values to copy
914 * @return *this
915 */
916 DynamicArray& operator=(std::initializer_list<T> const& list) {
917 assign(std::begin(list), std::end(list));
918 return *this;
919 }
920
921 /**
922 * @brief Copy Assignment: Replace the contents of this DynamicArray by copying values from
923 * another iterable container of compatible type.
924 *
925 * @tparam InputContainerT Another container type. Must support std::begin and std::end.
926 * @param other Container from which values will be copied.
927 * @return *this
928 */
929 template <
930 typename InputContainerT,
932 (!std::is_same_v<std::decay_t<InputContainerT>, DynamicArray> &&
933 sizeof(decltype(std::begin(std::declval<InputContainerT const&>()))) &&
934 sizeof(decltype(std::end(std::declval<InputContainerT const&>())))))>
935 DynamicArray& operator=(InputContainerT const& other) {
936 assign(std::begin(other), std::end(other));
937 return *this;
938 }
939
940 /**
941 * @brief Comparison returns true if the other array has the same size and all values are equal.
942 */
943 bool operator==(DynamicArray const& other) const {
944 auto s = size();
945 if (other.size() == s) {
946 for (size_type i = 0; i < s; ++i) {
947 if (other._begin[i] != _begin[i]) {
948 return false;
949 }
950 }
951 return true;
952 } else {
953 return false;
954 }
955 }
956
957 /**
958 * @brief Comparison returns false unless the other array has the same size and all values are
959 * equal.
960 */
961 MOCHI_FORCE_INLINE bool operator!=(DynamicArray const& other) const {
962 return !(*this == other);
963 }
964
965 private:
966 void GrowCapacity(size_type newCapacity) {
967 MOCHI_DARRAY_ASSERT(newCapacity > capacity(), "This method only increases capacity");
968 if (empty()) {
969 if (_begin) {
970 // Free previous allocation first, in case of a FILO allocator.
971 _allocator->deallocate(_begin, capacity() * sizeof(T), alignof(T));
972 }
973 _begin = _end = static_cast<T*>(_allocator->allocate(newCapacity * sizeof(T), alignof(T)));
974 _endCapacity = _begin + newCapacity;
975 } else {
976 auto oldSize = size();
977 auto* newBegin = static_cast<T*>(_allocator->allocate(newCapacity * sizeof(T), alignof(T)));
978 for (auto i = static_cast<ptrdiff_t>(oldSize) - 1; i >= 0; --i) {
979 new (&newBegin[i]) T(std::move(_begin[i])); // Move via placement new
980 if constexpr (!std::is_trivially_destructible_v<T>) {
981 _begin[i].~T(); // Destroy
982 }
983 }
984 _allocator->deallocate(_begin, capacity() * sizeof(T), alignof(T));
985 _begin = newBegin;
986 _end = newBegin + oldSize;
987 _endCapacity = newBegin + newCapacity;
988 }
989 }
990
991 size_type GetNextCapacity(size_type minCapacity) const {
992 // Jump to kGrowthPatternStartSize, then grow by 50% each time after that.
993 return std::max(std::max(minCapacity, kGrowthPatternStartSize), capacity() * 3 / 2);
994 }
995
996 static void DebugFillWithNaN(
997 [[maybe_unused]] void* rangeBegin,
998 [[maybe_unused]] void const* rangeEnd) {
999#if MOCHI_DARRAY_DEBUG
1000 // Fill as much of the range as we can with NaN values of type real.
1001 // This will help catch mistakes in case someone reads memory that they shouldn't.
1002 auto fillBeginAddr =
1003 Min(reinterpret_cast<size_type>(rangeEnd),
1004 RoundUp(reinterpret_cast<size_type>(rangeBegin), alignof(real)));
1005 auto fillEndAddr =
1006 Max(reinterpret_cast<size_type>(rangeBegin),
1007 RoundDown(reinterpret_cast<size_type>(rangeEnd), alignof(real)));
1008 auto* fillBegin = reinterpret_cast<std::byte*>(fillBeginAddr);
1009 auto* fillEnd = reinterpret_cast<std::byte*>(fillEndAddr);
1010 auto const nan = std::numeric_limits<real>::signaling_NaN();
1011 for (auto it = fillBegin; it < fillEnd; it += sizeof(nan)) {
1012 // Use memcpy instead of dereferencing a real* because of strict aliasing rules.
1013 memcpy(it, &nan, sizeof(nan));
1014 }
1015 // Because of alignment, the fill range might be smaller than the input range.
1016 // In that case, write zeros to the remaining bytes on either end.
1017 auto paddingSizeFront = fillBegin - reinterpret_cast<std::byte*>(rangeBegin);
1018 if (paddingSizeFront) {
1019 memset(rangeBegin, 0, paddingSizeFront);
1020 }
1021 auto paddingSizeBack = reinterpret_cast<std::byte const*>(rangeEnd) - fillEnd;
1022 if (paddingSizeBack) {
1023 memset(fillEnd, 0, paddingSizeBack);
1024 }
1025#endif // MOCHI_DARRAY_DEBUG
1026 }
1027
1028 static void DefaultConstructRange(T* rangeBegin, T const* rangeEnd) {
1029 if constexpr (std::is_trivially_default_constructible_v<T>) {
1030 auto numBytes =
1031 reinterpret_cast<std::intptr_t>(rangeEnd) - reinterpret_cast<std::intptr_t>(rangeBegin);
1032 memset(rangeBegin, 0, numBytes); // Zero-initialize
1033 } else {
1034 for (auto* it = rangeBegin; it < rangeEnd; ++it) {
1035 new (it) T; // Default construct
1036 }
1037 }
1038 }
1039
1040#if MOCHI_COMPILER_MSVC
1041#if _MSC_VER < 1944
1042 // [T255431885] MSVC versions before 19.44 can drop the final copy of an inlined loop.
1043 MOCHI_NO_INLINE
1044#endif
1045#endif
1046 static void CopyConstructRangeFromValue(T* rangeBegin, T const* rangeEnd, T const& value) {
1047 for (auto* it = rangeBegin; it < rangeEnd; ++it) {
1048 new (it) T(value); // Copy construct
1049 }
1050 }
1051
1052 template <class InputIt>
1053 static void CopyConstructRange(T* dstBegin, InputIt srcBegin, InputIt srcEnd) {
1054 // TODO(C++20): Replace by std::iter_value_t<InputIt>.
1055 using SrcT = std::remove_cv_t<typename std::iterator_traits<InputIt>::value_type>;
1056 if constexpr (
1057 std::is_trivially_copyable_v<T> && std::is_copy_assignable_v<T> &&
1058 std::is_same_v<SrcT, T>) {
1059 std::copy(srcBegin, srcEnd, dstBegin); // Copy assign. Works for any iterator type.
1060 } else {
1061 auto src = srcBegin;
1062 auto dst = dstBegin;
1063 for (; src != srcEnd; ++src, ++dst) {
1064 new (dst) T(*src); // Copy construct
1065 }
1066 }
1067 }
1068
1069 static void MoveConstructRange(T* dstBegin, T* srcBegin, size_type count) {
1070 if constexpr (std::is_trivially_move_constructible_v<T>) {
1071 if (count > 0) MOCHI_LIKELY {
1072 memcpy(dstBegin, srcBegin, count * sizeof(T));
1073 }
1074 } else {
1075 for (auto i = 0; i < count; ++i) {
1076 new (&dstBegin[i]) T(std::move(srcBegin[i])); // Move construct
1077 }
1078 }
1079 }
1080
1081 static void Destroy(T* it) {
1082 if constexpr (!std::is_trivially_destructible_v<T>) {
1083 it->~T();
1084 }
1085 DebugFillWithNaN(it, it + 1);
1086 }
1087
1088 static void DestroyRange(T* rangeBegin, T const* rangeEnd) {
1089 if constexpr (!std::is_trivially_destructible_v<T>) {
1090 if (rangeEnd > rangeBegin) MOCHI_LIKELY {
1091 // Destroy in reverse order in case of FILO allocator used within element
1092 auto* it = const_cast<T*>(rangeEnd);
1093 while (it != rangeBegin) {
1094 --it;
1095 it->~T();
1096 }
1097 }
1098 }
1099 DebugFillWithNaN(rangeBegin, rangeEnd);
1100 }
1101
1102#if MOCHI_DARRAY_DEBUG
1103 template <class InputIt>
1104 bool IsInThisArray(InputIt rangeBegin, InputIt rangeEnd) const {
1105 if constexpr (std::is_pointer_v<std::remove_reference_t<InputIt>>) {
1106 // Return true if the input range overlaps the memory used by this DynamicArray
1107 return !(
1108 (reinterpret_cast<T const*>(rangeBegin)) >= _endCapacity ||
1109 (reinterpret_cast<T const*>(rangeEnd) <= _begin));
1110 } else {
1111 // If input iterators are used (not raw pointers) then we'll assume they come from somewhere
1112 // else since DynamicArray does not use an iterator class.
1113 return false;
1114 }
1115 }
1116
1117 bool IsInThisArray(T const* ptr) const {
1118 return (ptr >= _begin) && (ptr < _end);
1119 }
1120#endif // MOCHI_DARRAY_DEBUG
1121
1122 // When overallocating, start with at least this capacity.
1123 static constexpr size_type kGrowthPatternStartSize = 8;
1124
1125 T* _begin = nullptr;
1126 T* _end = nullptr;
1127 T* _endCapacity = nullptr;
1128 Allocator* _allocator = GetDefaultAllocator();
1129};
1130
1131/**
1132 Utility Functions
1133*/
1134
1135// Specialization of Append found in container_utils.h
1136template <typename T, typename InBeginIterator, typename InEndIterator>
1138Append(DynamicArray<T>& out, InBeginIterator const& inBegin, InEndIterator const& inEnd) {
1139 out.append(inBegin, inEnd);
1140}
1141
1142// Specialization of Append found in container_utils.h
1143template <typename T, typename InContainer>
1144MOCHI_FORCE_INLINE void Append(DynamicArray<T>& out, InContainer const& inContainer) {
1145 out.append(std::begin(inContainer), std::end(inContainer));
1146}
1147
1148// Specialization of Append found in container_utils.h
1149// For each input value, add valueToAdd and append to result to the output.
1150template <typename T, typename ContainerIn>
1151void AppendSum(DynamicArray<T>& out, ContainerIn const& in, T valueToAdd) {
1152 if (valueToAdd == T(0)) {
1153 Append(out, in);
1154 } else {
1155 auto outIndex = out.size();
1156 out.resize_noinit(outIndex + std::size(in));
1157 for (auto const& x : in) {
1158 out[outIndex++] = x + valueToAdd;
1159 }
1160 }
1161}
1162
1163/**
1164 Type Traits
1165*/
1166
1167namespace details {
1168template <class ContainerT>
1169struct IsDynamicArrayDef : public std::false_type {};
1170template <class T>
1171struct IsDynamicArrayDef<DynamicArray<T>> : public std::true_type {};
1172} // namespace details
1173
1174// IsDynamicArray<ContainerT> is true iff ContainerT is a type of the form DynamicArray<T>
1175template <class ContainerT>
1176static constexpr bool kIsDynamicArray = // Note: nvcc thinks details without superdex:: is ambiguous.
1177 superdex::details::IsDynamicArrayDef<std::decay_t<ContainerT>>::value;
1178
1179// Class Template Argument Deduction (CTAD) guides
1180template <
1181 typename InputIt,
1182 MOCHI_CONCEPT((std::is_base_of_v<
1183 std::input_iterator_tag,
1184 typename std::iterator_traits<InputIt>::iterator_category>))>
1187
1188} // namespace superdex
1189
1190// Reflection support
1191#if MOCHI_USE_REFLECTION
1192namespace superdex::details {
1193
1194// Reflection type info for DynamicArray. For memcopy-safe element types, the binary serialization
1195// writes the element count followed by all elements in one copy, avoiding the per-element virtual
1196// calls of SReflect::ArrayTypeInfo. For arithmetic and struct elements, this produces the same
1197// bytes as the per-element path. Fixed-size array elements (e.g. Real3, Quaternion) are written
1198// without the per-element count of that path; binary captures are only exchanged between processes
1199// of the same build, which agree on the format.
1200template <class T>
1201class DynamicArrayTypeInfo final : public SReflect::ArrayTypeInfo {
1202 public:
1203 [[nodiscard]] bool CanResize() const override {
1204 return true;
1205 }
1206
1207 size_t GetNumElements(void const* obj) const override {
1208 return Get(obj).size();
1209 }
1210
1211 bool SetNumElements(void* obj, size_t numElements) const override {
1212 Get(obj).resize(numElements);
1213 return true;
1214 }
1215
1216 void* GetElement(void* obj, size_t i) const override {
1217 return &Get(obj)[i];
1218 }
1219
1220 void const* GetElement(void const* obj, size_t i) const override {
1221 return &Get(obj)[i];
1222 }
1223
1224 [[nodiscard]] bool IsMemCopySafe() const override {
1225 return false;
1226 }
1227
1228 protected:
1229 bool SerializeToBytesInner(void const* src, SReflect::StreamWriter& dst) const override {
1230 if constexpr (std::is_trivially_copyable_v<T>) {
1231 if (_innerTypeInfo->IsMemCopySafe()) {
1232 auto const& arr = Get(src);
1233 size_t const numElements = arr.size();
1234 // An empty array may have no storage, and stream copies must not get a null pointer.
1235 return dst.Write(&numElements, sizeof(numElements)) &&
1236 (numElements == 0 || dst.Write(arr.data(), numElements * sizeof(T)));
1237 }
1238 }
1239 return ArrayTypeInfo::SerializeToBytesInner(src, dst);
1240 }
1241
1242 bool DeserializeFromBytesInner(SReflect::StreamReader& src, void* dst) const override {
1243 if constexpr (std::is_trivially_copyable_v<T>) {
1244 if (_innerTypeInfo->IsMemCopySafe()) {
1245 size_t numElements = 0;
1246 // Reject counts whose byte size overflows, which would allocate an undersized array.
1247 if (!src.Read(&numElements, sizeof(numElements)) ||
1248 numElements > std::numeric_limits<size_t>::max() / sizeof(T)) {
1249 return false;
1250 }
1251 auto& arr = Get(dst);
1252 arr.resize_noinit(numElements);
1253 return numElements == 0 || src.Read(arr.data(), numElements * sizeof(T));
1254 }
1255 }
1256 return ArrayTypeInfo::DeserializeFromBytesInner(src, dst);
1257 }
1258
1259 private:
1260 static DynamicArray<T>& Get(void* obj) {
1261 return *static_cast<DynamicArray<T>*>(obj);
1262 }
1263
1264 static DynamicArray<T> const& Get(void const* obj) {
1265 return *static_cast<DynamicArray<T> const*>(obj);
1266 }
1267};
1268
1269} // namespace superdex::details
1270
1271template <class T>
1272struct SReflectTypeTraits<superdex::DynamicArray<T>> {
1273 static constexpr SReflect::CoreType coreType = SReflect::CoreType::CT_array;
1274 static SReflect::ArrayTypeInfo const& GetTypeInfo() {
1275 using ArrT = superdex::DynamicArray<T>;
1276 static auto* s_typeInfo =
1277 SReflect::MakeDynamicArrayTypeInfo<superdex::details::DynamicArrayTypeInfo<T>, ArrT, T>(
1278 "superdex::DynamicArray", true);
1279 return *s_typeInfo;
1280 }
1281};
1282#endif // MOCHI_USE_REFLECTION
Virtual interface class for memory allocation and deallocation.
Definition allocator.h:47
A dynamically resizable array with syntax and behavior similar to std::pmr::vector.
DynamicArray()=default
Construct an empty DynamicArray with the default allocator.
DynamicArray(size_type size, FromT const &defaultValue, Allocator *allocator=GetDefaultAllocator())
Construct a DynamicArray filled with copies of the specified value.
size_type size() const
Get the number of elements in the array.
void append(InputIt rangeBegin, InputIt rangeEnd)
Add values to the end of this DynamicArray by copying them from the half-open range [rangeBegin,...
T const & back() const
Get a const reference to the last element.
const_iterator cbegin() const
Get a const iterator pointing to the beginning of the array.
DynamicArray(DynamicArray const &other)
Copy construct from another DynamicArray.
T & push_back()
Default construct a new element at the end of the array.
void reset(Args &&... args)
Reset the state of this DynamicArray using the arguments from any constructor.
iterator begin()
Get an iterator pointing to the beginning of the array.
void resize_noinit(size_type newSize)
Set the size but do not initialize any new elements.
DynamicArray & operator=(DynamicArray const &other)
Copy Assignment: Replace the contents of this DynamicArray by copying values from another one.
void push_back(T &&value)
Move the value to a new element at the end of the array.
DynamicArray & operator=(std::initializer_list< T > const &list)
Copy Assignment: Replace the contents of this DynamicArray by copying values from a std::initializer_...
Allocator * get_allocator() const
Get a pointer to the polymorphic allocator.
void resize(size_type newSize)
Set the size.
void resize(size_type newSize, T const &value)
Set the size.
T & operator[](size_type i)
Get a reference to the value at index i.
DynamicArray(size_type size, Allocator *allocator=GetDefaultAllocator())
Construct a DynamicArray with an initial size.
DynamicArray & operator=(DynamicArray &&other)
Move Assignment: Replace the contents of this DynamicArray by moving memory or values from another on...
bool operator==(DynamicArray const &other) const
Comparison returns true if the other array has the same size and all values are equal.
T const & front() const
Get a const reference to the first element.
DynamicArray(std::initializer_list< T > const &list, Allocator *allocator=GetDefaultAllocator())
Construct a DynamicArray and copy values from a std::initializer_list.
T const & operator[](size_type i) const
Get a reference to the value at index i.
T const * data() const
Get a const pointer to the first element.
T * data()
Get a pointer to the first element.
void erase(const_iterator it_)
Remove one element from this array.
void pop_back()
Remove the last element of the array (must not be empty).
void push_back(T const &value)
Copy the value to a new element at the end of the array.
void erase(const_iterator rangeBegin_, const_iterator rangeEnd_)
Remove the half-open range [rangeBegin, rangeEnd) from this array.
void assign(InputIt rangeBegin, InputIt rangeEnd)
Replace the contents of this DynamicArray by copying values from the half-open range [rangeBegin,...
const_iterator cend() const
Get a const iterator pointing to the next element AFTER the end of the array.
void erase_unordered(iterator it)
Remove one element from this array and swap the last element into its place.
DynamicArray(DynamicArray &&other) noexcept
Move construct from another DynamicArray.
bool empty() const
Return true if the array is empty (zero size).
size_type capacity() const
Get the number of elements that could fit in the array without allocating more memory.
DynamicArray(DynamicArray const &other, Allocator *allocator)
Construct a DynamicArray and copy values from another one.
const_iterator end() const
Get a const iterator pointing to the next element AFTER the end of the array.
void clear()
Set the size to zero.
void shrink_to_fit()
Ensure that the capacity (memory allocated) is no larger than the size (memory used).
bool operator!=(DynamicArray const &other) const
Comparison returns false unless the other array has the same size and all values are equal.
T & front()
Get a reference to the first element.
iterator end()
Get an iterator pointing to the next element AFTER the end of the array.
DynamicArray(Allocator *allocator)
Construct an empty DynamicArray with a specific allocator.
T & back()
Get a reference to the last element.
void reserve(size_type newCapacity)
Ensure that this array has at least the specified capacity.
DynamicArray & operator=(InputContainerT const &other)
Copy Assignment: Replace the contents of this DynamicArray by copying values from another iterable co...
~DynamicArray()
Destroy the DynamicArray object and all of its elements.
DynamicArray(InputIt rangeBegin, InputIt rangeEnd, Allocator *allocator=GetDefaultAllocator())
Construct a DynamicArray and copy values from the half-open range: [rangeBegin, rangeEnd).
DynamicArray(DynamicArray &&other, Allocator *allocator)
Construct a DynamicArray by moving memory or values from another one.
void emplace_back(Args &&... args)
Emplace a new element at the end of the array.
DynamicArray(InputContainerT const &other, Allocator *allocator=GetDefaultAllocator())
Construct a DynamicArray and copy values from another iterable container type like superdex::Span,...
void append(InputContainerT const &container)
Add values to the end of this DynamicArray by copying them from another iterable container.
const_iterator begin() const
Get a const iterator pointing to the beginning of the array.
#define MOCHI_DARRAY_ASSERT_FORWARD_ITERATOR(IteratorType)
#define MOCHI_DARRAY_ASSERT(cond,...)
#define MOCHI_CONCEPT(a)
#define MOCHI_UNLIKELY
#define MOCHI_FORCE_INLINE
#define MOCHI_LIKELY
constexpr T const & Min(T const &a, T const &b)
constexpr T RoundDown(T numToRound, T multiple)
constexpr T RoundUp(T numToRound, T multiple)
void Append(DynamicArray< T > &out, InBeginIterator const &inBegin, InEndIterator const &inEnd)
Utility Functions.
constexpr bool kIsResizeNoInitSafe
Helper variable template for IsResizeNoInitSafe.
DynamicArray(InputIt, InputIt, Allocator *=GetDefaultAllocator()) -> DynamicArray< typename std::iterator_traits< InputIt >::value_type >
Allocator * GetDefaultAllocator()
Get an instance of the DefaultAllocator class.
constexpr T const & Max(T const &a, T const &b)
void AppendSum(DynamicArray< T > &out, ContainerIn const &in, T valueToAdd)
Trait to determine if a type is safe for use with DynamicArray::resize_noinit.