Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_small_vector.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
59#ifndef TPL_SMALL_VECTOR_H
60#define TPL_SMALL_VECTOR_H
61
62#include <cstddef>
63#include <initializer_list>
64#include <iterator>
65#include <limits>
66#include <memory>
67#include <new>
68#include <type_traits>
69#include <utility>
70
71#include <ah-concepts.H>
72#include <ah-errors.H>
73
74namespace Aleph {
75
117template <typename T, size_t N = 8>
119{
120 static_assert(N > 0, "SmallVector requires a positive inline capacity");
121 static_assert(std::is_move_constructible_v<T>,
122 "SmallVector requires a move-constructible element type");
123
124 // Raw inline storage for the first N elements. The buffer is aligned as T so
125 // placement-new can construct T objects here without a separate heap allocation.
126 alignas(T) std::byte storage_[N * sizeof(T)];
128 size_t n_ = 0;
129 size_t cap_ = N;
130
131 T *inline_ptr() noexcept
132 {
133 return reinterpret_cast<T *>(storage_);
134 }
135
136 const T *inline_ptr() const noexcept
137 {
138 return reinterpret_cast<const T *>(storage_);
139 }
140
141 static T *allocate(size_t m)
142 {
143 return std::allocator<T>().allocate(m);
144 }
145
146 static void deallocate(T *p, size_t m) noexcept
147 {
148 std::allocator<T>().deallocate(p, m);
149 }
150
151 // Moves the elements into a fresh heap buffer of capacity new_cap
152 // (strong guarantee via move_if_noexcept) and releases the old buffer.
153 void relocate(const size_t new_cap)
154 {
155 T *np = allocate(new_cap);
156 size_t i = 0;
157 try
158 {
159 for (; i < n_; ++i)
160 ::new (static_cast<void *>(np + i)) T(std::move_if_noexcept(ptr_[i]));
161 }
162 catch (...)
163 {
164 std::destroy(np, np + i);
165 deallocate(np, new_cap);
166 throw;
167 }
168 std::destroy(ptr_, ptr_ + n_);
169 if (not is_small())
171 ptr_ = np;
172 cap_ = new_cap;
173 }
174
175 // Ensures room for at least min_cap elements, growing geometrically.
176 void grow(const size_t min_cap)
177 {
178 size_t new_cap = cap_;
179 while (new_cap < min_cap)
180 {
181 ah_overflow_error_if(new_cap > (static_cast<size_t>(-1) >> 1))
182 << "SmallVector::grow(): capacity overflow";
183 new_cap <<= 1;
184 }
185 relocate(new_cap);
186 }
187
188 // Takes over o's contents. *this must be empty and inline.
189 void steal(SmallVector &&o) noexcept(std::is_nothrow_move_constructible_v<T>)
190 {
191 if (o.is_small())
192 {
193 if constexpr (std::is_nothrow_move_constructible_v<T>)
194 {
195 for (; n_ < o.n_; ++n_)
196 ::new (static_cast<void *>(ptr_ + n_)) T(std::move(o.ptr_[n_]));
197 }
198 else
199 {
200 try
201 {
202 for (; n_ < o.n_; ++n_)
203 ::new (static_cast<void *>(ptr_ + n_)) T(std::move(o.ptr_[n_]));
204 }
205 catch (...)
206 {
207 release();
208 throw;
209 }
210 }
211 std::destroy(o.ptr_, o.ptr_ + o.n_);
212 o.n_ = 0;
213 }
214 else
215 {
216 ptr_ = o.ptr_;
217 cap_ = o.cap_;
218 n_ = o.n_;
219 o.ptr_ = o.inline_ptr();
220 o.cap_ = N;
221 o.n_ = 0;
222 }
223 }
224
225 // Destroys all elements and releases the heap buffer, back to inline.
226 void release() noexcept
227 {
228 std::destroy(ptr_, ptr_ + n_);
229 if (not is_small())
231 ptr_ = inline_ptr();
232 cap_ = N;
233 n_ = 0;
234 }
235
236public:
237 using Item_Type = T;
238 using value_type = T;
239 using size_type = size_t;
240 using iterator = T *;
241 using const_iterator = const T *;
242
244 SmallVector() noexcept : ptr_(inline_ptr()) {}
245
252 SmallVector(const size_t n, const T &value)
253 requires std::is_copy_constructible_v<T>
254 : ptr_(inline_ptr())
255 {
256 if (n > cap_)
257 grow(n);
258 try
259 {
260 for (; n_ < n; ++n_)
261 ::new (static_cast<void *>(ptr_ + n_)) T(value);
262 }
263 catch (...)
264 {
265 release();
266 throw;
267 }
268 }
269
274 SmallVector(std::initializer_list<T> l)
275 requires std::is_copy_constructible_v<T>
276 : ptr_(inline_ptr())
277 {
278 if (l.size() > cap_)
279 grow(l.size());
280 try
281 {
282 for (const T &x : l)
283 {
284 ::new (static_cast<void *>(ptr_ + n_)) T(x);
285 ++n_;
286 }
287 }
288 catch (...)
289 {
290 release();
291 throw;
292 }
293 }
294
301 template <std::input_iterator It>
302 SmallVector(It first, It last) : ptr_(inline_ptr())
303 {
304 try
305 {
306 for (; first != last; ++first)
307 append(*first);
308 }
309 catch (...)
310 {
311 release();
312 throw;
313 }
314 }
315
318 requires std::is_copy_constructible_v<T>
319 : ptr_(inline_ptr())
320 {
321 if (v.n_ > cap_)
322 grow(v.n_);
323 try
324 {
325 for (; n_ < v.n_; ++n_)
326 ::new (static_cast<void *>(ptr_ + n_)) T(v.ptr_[n_]);
327 }
328 catch (...)
329 {
330 release();
331 throw;
332 }
333 }
334
340 SmallVector(SmallVector &&v) noexcept(std::is_nothrow_move_constructible_v<T>)
341 : ptr_(inline_ptr())
342 {
343 steal(std::move(v));
344 }
345
348 requires std::is_copy_constructible_v<T>
349 {
350 if (this == &v)
351 return *this;
352 release();
353 if (v.n_ > cap_)
354 grow(v.n_);
355 for (; n_ < v.n_; ++n_)
356 ::new (static_cast<void *>(ptr_ + n_)) T(v.ptr_[n_]);
357 return *this;
358 }
359
361 SmallVector &operator = (SmallVector &&v) noexcept(std::is_nothrow_move_constructible_v<T>)
362 {
363 if (this == &v)
364 return *this;
365 release();
366 steal(std::move(v));
367 return *this;
368 }
369
371 {
372 release();
373 }
374
382 void swap(SmallVector &v) noexcept(std::is_nothrow_move_constructible_v<T>)
383 {
384 if (not is_small() and not v.is_small())
385 {
386 std::swap(ptr_, v.ptr_);
387 std::swap(n_, v.n_);
388 std::swap(cap_, v.cap_);
389 return;
390 }
391 SmallVector tmp(std::move(*this));
392 *this = std::move(v);
393 v = std::move(tmp);
394 }
395
396 // -- capacity -------------------------------------------------------------
397
399 [[nodiscard]] size_t size() const noexcept
400 {
401 return n_;
402 }
403
405 [[nodiscard]] size_t capacity() const noexcept
406 {
407 return cap_;
408 }
409
411 [[nodiscard]] bool is_empty() const noexcept
412 {
413 return n_ == 0;
414 }
415
417 [[nodiscard]] bool is_small() const noexcept
418 {
419 return ptr_ == inline_ptr();
420 }
421
426 void reserve(const size_t cap)
427 {
428 if (cap > cap_)
429 grow(cap);
430 }
431
436 void empty() noexcept
437 {
438 std::destroy(ptr_, ptr_ + n_);
439 n_ = 0;
440 }
441
443 void clear() noexcept
444 {
445 empty();
446 }
447
448 // -- element access -------------------------------------------------------
449
455 [[nodiscard]] T &operator [] (size_t i)
456 {
457 ah_out_of_range_error_if(i >= n_) << "SmallVector: index out of range";
458 return ptr_[i];
459 }
460
462 [[nodiscard]] const T &operator [] (size_t i) const
463 {
464 ah_out_of_range_error_if(i >= n_) << "SmallVector: index out of range";
465 return ptr_[i];
466 }
467
469 [[nodiscard]] T &operator () (size_t i) noexcept
470 {
471 return ptr_[i];
472 }
473
475 [[nodiscard]] const T &operator () (size_t i) const noexcept
476 {
477 return ptr_[i];
478 }
479
484 [[nodiscard]] T &get_first()
485 {
486 ah_underflow_error_if(n_ == 0) << "SmallVector::get_first(): empty";
487 return ptr_[0];
488 }
489
491 [[nodiscard]] const T &get_first() const
492 {
493 ah_underflow_error_if(n_ == 0) << "SmallVector::get_first(): empty";
494 return ptr_[0];
495 }
496
501 [[nodiscard]] T &get_last()
502 {
503 ah_underflow_error_if(n_ == 0) << "SmallVector::get_last(): empty";
504 return ptr_[n_ - 1];
505 }
506
508 [[nodiscard]] const T &get_last() const
509 {
510 ah_underflow_error_if(n_ == 0) << "SmallVector::get_last(): empty";
511 return ptr_[n_ - 1];
512 }
513
515 [[nodiscard]] T *data() noexcept
516 {
517 return ptr_;
518 }
519
521 [[nodiscard]] const T *data() const noexcept
522 {
523 return ptr_;
524 }
525
526 // -- modifiers ------------------------------------------------------------
527
536 template <class... Args>
537 T &emplace_back(Args &&...args)
538 {
539 if (n_ == cap_)
540 {
541 T tmp(std::forward<Args>(args)...);
542 grow(n_ + 1);
543 ::new (static_cast<void *>(ptr_ + n_)) T(std::move(tmp));
544 }
545 else
546 ::new (static_cast<void *>(ptr_ + n_)) T(std::forward<Args>(args)...);
547 return ptr_[n_++];
548 }
549
556 T &append(const T &item)
557 requires std::is_copy_constructible_v<T>
558 {
559 return emplace_back(item);
560 }
561
568 T &append(T &&item)
569 {
570 return emplace_back(std::move(item));
571 }
572
614 void append_range(const T *first, const size_t count)
615 requires std::is_copy_constructible_v<T>
616 {
617 if (count == 0)
618 return;
619 ah_invalid_argument_if(first == nullptr)
620 << "SmallVector::append_range(): null source pointer";
621 // Checked *before* computing `n_ + count`, not after: for an
622 // adversarial or mistaken huge `count`, the raw sum can wrap around
623 // `size_t` and come out `<= cap_`, which would skip the `grow()`
624 // call below entirely and then `memcpy` (or the placement-new loop)
625 // straight past the end of the real, too-small buffer.
626 ah_overflow_error_if(count > std::numeric_limits<size_t>::max() - n_)
627 << "SmallVector::append_range(): count overflows size_t when added "
628 "to the current size";
629 if (n_ + count > cap_)
630 grow(n_ + count);
631 if constexpr (std::is_trivially_copyable_v<T>)
632 {
633 // std::uninitialized_copy_n, not a raw memcpy: copying the object
634 // representation into storage that holds no object yet only
635 // implicitly starts a `T` object's lifetime there (C++20
636 // [basic.types.general]) when `T` is an *implicit-lifetime*
637 // type -- trivially copyable does not by itself guarantee that
638 // (e.g. a type whose only non-deleted special member is a
639 // trivial assignment operator, with every constructor deleted,
640 // is trivially copyable but not implicit-lifetime). Standard
641 // library implementations detect the trivially-copyable case
642 // and lower this to the same memcpy, so this costs nothing.
643 std::uninitialized_copy_n(first, count, ptr_ + n_);
644 n_ += count;
645 }
646 else
647 {
648 size_t i = 0;
649 try
650 {
651 for (; i < count; ++i)
652 ::new (static_cast<void *>(ptr_ + n_ + i)) T(first[i]);
653 }
654 catch (...)
655 {
656 std::destroy(ptr_ + n_, ptr_ + n_ + i);
657 throw;
658 }
659 n_ += count;
660 }
661 }
662
664 T &push_back(const T &item)
665 requires std::is_copy_constructible_v<T>
666 {
667 return append(item);
668 }
669
671 T &push_back(T &&item)
672 {
673 return append(std::move(item));
674 }
675
682 {
683 ah_underflow_error_if(n_ == 0) << "SmallVector::remove_last(): empty";
684 T ret = std::move(ptr_[n_ - 1]);
685 std::destroy_at(ptr_ + --n_);
686 return ret;
687 }
688
693 void pop_back()
694 {
695 ah_underflow_error_if(n_ == 0) << "SmallVector::pop_back(): empty";
696 std::destroy_at(ptr_ + --n_);
697 }
698
707 T &insert(size_t pos, T item)
708 requires std::is_move_assignable_v<T>
709 {
710 ah_out_of_range_error_if(pos > n_) << "SmallVector::insert(): position out of range";
711 if (n_ == cap_)
712 grow(n_ + 1);
713 if (pos == n_)
714 {
715 ::new (static_cast<void *>(ptr_ + n_)) T(std::move(item));
716 return ptr_[n_++];
717 }
718 ::new (static_cast<void *>(ptr_ + n_)) T(std::move(ptr_[n_ - 1]));
719 for (size_t i = n_ - 1; i > pos; --i)
720 ptr_[i] = std::move(ptr_[i - 1]);
721 ptr_[pos] = std::move(item);
722 ++n_;
723 return ptr_[pos];
724 }
725
731 void erase(const size_t pos)
732 requires std::is_move_assignable_v<T>
733 {
734 ah_out_of_range_error_if(pos >= n_) << "SmallVector::erase(): position out of range";
735 for (size_t i = pos; i + 1 < n_; ++i)
736 ptr_[i] = std::move(ptr_[i + 1]);
737 std::destroy_at(ptr_ + --n_);
738 }
739
740 // -- iteration ------------------------------------------------------------
741
743 iterator begin() noexcept
744 {
745 return ptr_;
746 }
747
749 iterator end() noexcept
750 {
751 return ptr_ + n_;
752 }
753
755 const_iterator begin() const noexcept
756 {
757 return ptr_;
758 }
759
761 const_iterator end() const noexcept
762 {
763 return ptr_ + n_;
764 }
765
767 const_iterator cbegin() const noexcept
768 {
769 return ptr_;
770 }
771
773 const_iterator cend() const noexcept
774 {
775 return ptr_ + n_;
776 }
777
787 template <class Operation>
789 bool traverse(Operation operation)
790 {
791 for (size_t i = 0; i < n_; ++i)
792 if (not operation(ptr_[i]))
793 return false;
794 return true;
795 }
796
802 template <class Operation>
804 bool traverse(Operation operation) const
805 {
806 for (size_t i = 0; i < n_; ++i)
807 if (not operation(std::as_const(ptr_[i])))
808 return false;
809 return true;
810 }
811
812 // -- comparison -----------------------------------------------------------
813
819 template <size_t M>
820 bool operator == (const SmallVector<T, M> &v) const
821 {
822 if (n_ != v.size())
823 return false;
824 for (size_t i = 0; i < n_; ++i)
825 if (not (ptr_[i] == v(i)))
826 return false;
827 return true;
828 }
829
831 template <size_t M>
832 bool operator != (const SmallVector<T, M> &v) const
833 {
834 return not (*this == v);
835 }
836};
837
838} // end namespace Aleph
839
840#endif // TPL_SMALL_VECTOR_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_underflow_error_if(C)
Throws std::underflow_error if condition holds.
Definition ah-errors.H:517
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Contiguous dynamic array with N elements of inline storage.
const_iterator end() const noexcept
Const iterator past the last element. O(1).
void relocate(const size_t new_cap)
static void deallocate(T *p, size_t m) noexcept
T & push_back(const T &item)
STL-style alias of append(const T &).
size_t size_type
STL convention: size type.
size_t capacity() const noexcept
Return the current capacity (inline or heap). O(1).
size_t size() const noexcept
Return the number of stored elements. O(1).
bool traverse(Operation operation)
Traverse elements in order while operation returns true.
void reserve(const size_t cap)
Reserve capacity for at least cap elements.
const T * const_iterator
Random-access const iterator.
SmallVector(It first, It last)
Construct from an iterator range.
SmallVector(const SmallVector &v)
Copy constructor (requires copyable T).
T & emplace_back(Args &&...args)
Construct an element in place at the end.
const_iterator cend() const noexcept
Const iterator past the last element. O(1).
T & get_last()
Last element (checked).
const_iterator begin() const noexcept
Const iterator to the first element. O(1).
void append_range(const T *first, const size_t count)
Append count copies from [first, first + count), in order.
T & append(const T &item)
Append a copy of item.
SmallVector() noexcept
Construct an empty vector using the inline storage. Never allocates.
void empty() noexcept
Destroy all elements (Aleph convention).
iterator end() noexcept
Iterator past the last element. O(1).
T * data() noexcept
Pointer to the contiguous element storage. O(1).
void steal(SmallVector &&o) noexcept(std::is_nothrow_move_constructible_v< T >)
SmallVector(const size_t n, const T &value)
Construct with n copies of value.
static T * allocate(size_t m)
T & get_first()
First element (checked).
T & operator()(size_t i) noexcept
Unchecked access to the i-th element (must be < size()).
void swap(SmallVector &v) noexcept(std::is_nothrow_move_constructible_v< T >)
Swap contents with v.
const T & get_first() const
See get_first().
bool is_small() const noexcept
Return true while the elements still live in the inline buffer. O(1).
T & append(T &&item)
Append item by moving.
void release() noexcept
T * inline_ptr() noexcept
T remove_last()
Remove and return the last element.
T value_type
STL convention: value type.
bool operator==(const SmallVector< T, M > &v) const
Equality: same size and pairwise equal elements.
std::byte storage_[N *sizeof(T)]
SmallVector & operator=(const SmallVector &v)
Copy assignment (requires copyable T).
bool traverse(Operation operation) const
Const traversal in order while operation returns true.
T & insert(size_t pos, T item)
Insert an element at position pos, shifting the tail right.
void pop_back()
Remove the last element (STL style).
const T * data() const noexcept
See data().
SmallVector(SmallVector &&v) noexcept(std::is_nothrow_move_constructible_v< T >)
Move constructor.
iterator begin() noexcept
Iterator to the first element. O(1).
T & operator[](size_t i)
Checked access to the i-th element.
bool operator!=(const SmallVector< T, M > &v) const
Inequality: negation of operator==.
const T * inline_ptr() const noexcept
void erase(const size_t pos)
Remove the element at position pos, shifting the tail left.
bool is_empty() const noexcept
Return true if no elements are stored. O(1).
SmallVector(std::initializer_list< T > l)
Construct from an initializer list.
T * iterator
Random-access iterator.
const_iterator cbegin() const noexcept
Const iterator to the first element. O(1).
T & push_back(T &&item)
STL-style alias of append(T &&).
void grow(const size_t min_cap)
void clear() noexcept
Destroy all elements. Alias of empty(). Capacity is kept.
T Item_Type
Aleph convention: element type.
const T & get_last() const
See get_last().
f(args...) is a valid call whose result is usable as a condition.
#define N
Definition fib.C:294
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
DynList< int > l