blob: 501217558c9dae04158b2d1a75386800f88d61b9 [file] [log] [blame]
Dominik Laskowski6fdf1142020-10-07 12:09:09 -07001/*
2 * Copyright 2020 The Android Open Source Project
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
Dominik Laskowski5444fc82020-11-24 13:41:10 -080019#include <ftl/array_traits.h>
20#include <ftl/initializer_list.h>
Dominik Laskowski0bacf272020-10-22 14:08:27 -070021
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070022#include <algorithm>
23#include <cassert>
24#include <iterator>
25#include <memory>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070026#include <type_traits>
27#include <utility>
28
29namespace android::ftl {
30
Dominik Laskowski5444fc82020-11-24 13:41:10 -080031constexpr struct IteratorRangeTag {} kIteratorRange;
Dominik Laskowski03572372020-10-27 22:36:00 -070032
Dominik Laskowski5444fc82020-11-24 13:41:10 -080033// Fixed-capacity, statically allocated counterpart of std::vector. Like std::array, StaticVector
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070034// allocates contiguous storage for N elements of type T at compile time, but stores at most (rather
35// than exactly) N elements. Unlike std::array, its default constructor does not require T to have a
Dominik Laskowskiccd50a42020-10-30 19:56:38 -070036// default constructor, since elements are constructed in place as the vector grows. Operations that
Dominik Laskowski03572372020-10-27 22:36:00 -070037// insert an element (emplace_back, push_back, etc.) fail when the vector is full. The API otherwise
38// adheres to standard containers, except the unstable_erase operation that does not preserve order,
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070039// and the replace operation that destructively emplaces.
40//
Dominik Laskowski5444fc82020-11-24 13:41:10 -080041// StaticVector<T, 1> is analogous to an iterable std::optional.
42// StaticVector<T, 0> is an error.
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070043//
44// Example usage:
45//
46// ftl::StaticVector<char, 3> vector;
47// assert(vector.empty());
48//
49// vector = {'a', 'b'};
50// assert(vector.size() == 2u);
51//
52// vector.push_back('c');
53// assert(vector.full());
54//
55// assert(!vector.push_back('d'));
56// assert(vector.size() == 3u);
57//
58// vector.unstable_erase(vector.begin());
59// assert(vector == (ftl::StaticVector{'c', 'b'}));
60//
61// vector.pop_back();
62// assert(vector.back() == 'c');
63//
64// const char array[] = "hi";
65// vector = ftl::StaticVector(array);
66// assert(vector == (ftl::StaticVector{'h', 'i', '\0'}));
67//
Dominik Laskowskiccd50a42020-10-30 19:56:38 -070068// ftl::StaticVector strings = ftl::init::list<std::string>("abc")
69// ("123456", 3u)
70// (3u, '?');
71// assert(strings.size() == 3u);
72// assert(strings[0] == "abc");
73// assert(strings[1] == "123");
74// assert(strings[2] == "???");
75//
Dominik Laskowski5444fc82020-11-24 13:41:10 -080076template <typename T, std::size_t N>
Dominik Laskowski0bacf272020-10-22 14:08:27 -070077class StaticVector final : ArrayTraits<T>,
78 ArrayIterators<StaticVector<T, N>, T>,
79 ArrayComparators<StaticVector> {
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070080 static_assert(N > 0);
81
Dominik Laskowski0bacf272020-10-22 14:08:27 -070082 using ArrayTraits<T>::construct_at;
83
84 using Iter = ArrayIterators<StaticVector, T>;
85 friend Iter;
86
Dominik Laskowski03572372020-10-27 22:36:00 -070087 // There is ambiguity when constructing from two iterator-like elements like pointers:
88 // they could be an iterator range, or arguments for in-place construction. Assume the
89 // latter unless they are input iterators and cannot be used to construct elements. If
90 // the former is intended, the caller can pass an IteratorRangeTag to disambiguate.
91 template <typename I, typename Traits = std::iterator_traits<I>>
Dominik Laskowski5444fc82020-11-24 13:41:10 -080092 using is_input_iterator = std::conjunction<
Dominik Laskowski03572372020-10-27 22:36:00 -070093 std::is_base_of<std::input_iterator_tag, typename Traits::iterator_category>,
94 std::negation<std::is_constructible<T, I>>>;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070095
96public:
Dominik Laskowski0bacf272020-10-22 14:08:27 -070097 FTL_ARRAY_TRAIT(T, value_type);
98 FTL_ARRAY_TRAIT(T, size_type);
99 FTL_ARRAY_TRAIT(T, difference_type);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700100
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700101 FTL_ARRAY_TRAIT(T, pointer);
102 FTL_ARRAY_TRAIT(T, reference);
103 FTL_ARRAY_TRAIT(T, iterator);
104 FTL_ARRAY_TRAIT(T, reverse_iterator);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700105
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700106 FTL_ARRAY_TRAIT(T, const_pointer);
107 FTL_ARRAY_TRAIT(T, const_reference);
108 FTL_ARRAY_TRAIT(T, const_iterator);
109 FTL_ARRAY_TRAIT(T, const_reverse_iterator);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700110
111 // Creates an empty vector.
112 StaticVector() = default;
113
114 // Copies and moves a vector, respectively.
Dominik Laskowski03572372020-10-27 22:36:00 -0700115 StaticVector(const StaticVector& other)
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800116 : StaticVector(kIteratorRange, other.begin(), other.end()) {}
117
118 StaticVector(StaticVector&& other) { swap<true>(other); }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700119
120 // Copies at most N elements from a smaller convertible vector.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800121 template <typename U, std::size_t M, typename = std::enable_if_t<M <= N>>
Dominik Laskowski03572372020-10-27 22:36:00 -0700122 StaticVector(const StaticVector<U, M>& other)
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800123 : StaticVector(kIteratorRange, other.begin(), other.end()) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700124
125 // Copies at most N elements from an array.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800126 template <typename U, std::size_t M>
Dominik Laskowski03572372020-10-27 22:36:00 -0700127 explicit StaticVector(U (&array)[M])
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800128 : StaticVector(kIteratorRange, std::begin(array), std::end(array)) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700129
130 // Copies at most N elements from the range [first, last).
Dominik Laskowski03572372020-10-27 22:36:00 -0700131 //
132 // IteratorRangeTag disambiguates with initialization from two iterator-like elements.
133 //
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800134 template <typename Iterator, typename = std::enable_if_t<is_input_iterator<Iterator>{}>>
135 StaticVector(Iterator first, Iterator last) : StaticVector(kIteratorRange, first, last) {
Dominik Laskowski03572372020-10-27 22:36:00 -0700136 using V = typename std::iterator_traits<Iterator>::value_type;
137 static_assert(std::is_constructible_v<value_type, V>, "Incompatible iterator range");
138 }
139
140 template <typename Iterator>
141 StaticVector(IteratorRangeTag, Iterator first, Iterator last)
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800142 : size_(std::min(max_size(), static_cast<size_type>(std::distance(first, last)))) {
143 std::uninitialized_copy(first, first + size_, begin());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700144 }
145
146 // Constructs at most N elements. The template arguments T and N are inferred using the
147 // deduction guide defined below. Note that T is determined from the first element, and
148 // subsequent elements must have convertible types:
149 //
150 // ftl::StaticVector vector = {1, 2, 3};
151 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<int, 3>>);
152 //
153 // const auto copy = "quince"s;
154 // auto move = "tart"s;
155 // ftl::StaticVector vector = {copy, std::move(move)};
156 //
157 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 2>>);
158 //
159 template <typename E, typename... Es,
160 typename = std::enable_if_t<std::is_constructible_v<value_type, E>>>
161 StaticVector(E&& element, Es&&... elements)
162 : StaticVector(std::index_sequence<0>{}, std::forward<E>(element),
163 std::forward<Es>(elements)...) {
164 static_assert(sizeof...(elements) < N, "Too many elements");
165 }
166
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700167 // Constructs at most N elements in place by forwarding per-element constructor arguments. The
168 // template arguments T and N are inferred using the deduction guide defined below. The syntax
169 // for listing arguments is as follows:
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700170 //
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700171 // ftl::StaticVector vector = ftl::init::list<std::string>("abc")()(3u, '?');
172 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700173 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 3>>);
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700174 // assert(vector.full());
175 // assert(vector[0] == "abc");
176 // assert(vector[1].empty());
177 // assert(vector[2] == "???");
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700178 //
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800179 template <typename U, std::size_t Size, std::size_t... Sizes, typename... Types>
180 StaticVector(InitializerList<U, std::index_sequence<Size, Sizes...>, Types...>&& list)
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700181 : StaticVector(std::index_sequence<0, 0, Size>{}, std::make_index_sequence<Size>{},
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800182 std::index_sequence<Sizes...>{}, list.tuple) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700183
184 ~StaticVector() { std::destroy(begin(), end()); }
185
186 StaticVector& operator=(const StaticVector& other) {
187 StaticVector copy(other);
188 swap(copy);
189 return *this;
190 }
191
192 StaticVector& operator=(StaticVector&& other) {
193 std::destroy(begin(), end());
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800194 size_ = 0;
195 swap<true>(other);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700196 return *this;
197 }
198
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800199 // IsEmpty enables a fast path when the vector is known to be empty at compile time.
200 template <bool IsEmpty = false>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700201 void swap(StaticVector&);
202
Dominik Laskowski03572372020-10-27 22:36:00 -0700203 static constexpr size_type max_size() { return N; }
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800204 size_type size() const { return size_; }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700205
206 bool empty() const { return size() == 0; }
207 bool full() const { return size() == max_size(); }
208
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800209 iterator begin() { return std::launder(reinterpret_cast<pointer>(data_)); }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700210 iterator end() { return begin() + size(); }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700211
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700212 using Iter::begin;
213 using Iter::end;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700214
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700215 using Iter::cbegin;
216 using Iter::cend;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700217
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700218 using Iter::rbegin;
219 using Iter::rend;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700220
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700221 using Iter::crbegin;
222 using Iter::crend;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700223
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700224 using Iter::last;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700225
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700226 using Iter::back;
227 using Iter::front;
228
229 using Iter::operator[];
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700230
Dominik Laskowski03572372020-10-27 22:36:00 -0700231 // Replaces an element, and returns a reference to it. The iterator must be dereferenceable, so
232 // replacing at end() is erroneous.
233 //
234 // The element is emplaced via move constructor, so type T does not need to define copy/move
235 // assignment, e.g. its data members may be const.
236 //
237 // The arguments may directly or indirectly refer to the element being replaced.
238 //
239 // Iterators to the replaced element point to its replacement, and others remain valid.
240 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700241 template <typename... Args>
Dominik Laskowski03572372020-10-27 22:36:00 -0700242 reference replace(const_iterator it, Args&&... args) {
243 value_type element{std::forward<Args>(args)...};
244 std::destroy_at(it);
245 // This is only safe because exceptions are disabled.
246 return *construct_at(it, std::move(element));
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700247 }
248
249 // Appends an element, and returns an iterator to it. If the vector is full, the element is not
Dominik Laskowski03572372020-10-27 22:36:00 -0700250 // inserted, and the end() iterator is returned.
251 //
252 // On success, the end() iterator is invalidated.
253 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700254 template <typename... Args>
255 iterator emplace_back(Args&&... args) {
256 if (full()) return end();
257 const iterator it = construct_at(end(), std::forward<Args>(args)...);
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800258 ++size_;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700259 return it;
260 }
261
Dominik Laskowski03572372020-10-27 22:36:00 -0700262 // Appends an element unless the vector is full, and returns whether the element was inserted.
263 //
264 // On success, the end() iterator is invalidated.
265 //
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700266 bool push_back(const value_type& v) {
267 // Two statements for sequence point.
268 const iterator it = emplace_back(v);
269 return it != end();
270 }
271
272 bool push_back(value_type&& v) {
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700273 // Two statements for sequence point.
274 const iterator it = emplace_back(std::move(v));
275 return it != end();
276 }
277
Dominik Laskowski03572372020-10-27 22:36:00 -0700278 // Removes the last element. The vector must not be empty, or the call is erroneous.
279 //
280 // The last() and end() iterators are invalidated.
281 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700282 void pop_back() { unstable_erase(last()); }
283
Dominik Laskowski03572372020-10-27 22:36:00 -0700284 // Erases an element, but does not preserve order. Rather than shifting subsequent elements,
285 // this moves the last element to the slot of the erased element.
286 //
287 // The last() and end() iterators, as well as those to the erased element, are invalidated.
288 //
289 void unstable_erase(const_iterator it) {
290 std::destroy_at(it);
291 if (it != last()) {
292 // Move last element and destroy its source for destructor side effects. This is only
293 // safe because exceptions are disabled.
294 construct_at(it, std::move(back()));
295 std::destroy_at(last());
296 }
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800297 --size_;
Dominik Laskowski03572372020-10-27 22:36:00 -0700298 }
299
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700300private:
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700301 // Recursion for variadic constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800302 template <std::size_t I, typename E, typename... Es>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700303 StaticVector(std::index_sequence<I>, E&& element, Es&&... elements)
304 : StaticVector(std::index_sequence<I + 1>{}, std::forward<Es>(elements)...) {
305 construct_at(begin() + I, std::forward<E>(element));
306 }
307
308 // Base case for variadic constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800309 template <std::size_t I>
310 explicit StaticVector(std::index_sequence<I>) : size_(I) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700311
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700312 // Recursion for in-place constructor.
313 //
314 // Construct element I by extracting its arguments from the InitializerList tuple. ArgIndex
315 // is the position of its first argument in Args, and ArgCount is the number of arguments.
316 // The Indices sequence corresponds to [0, ArgCount).
317 //
318 // The Sizes sequence lists the argument counts for elements after I, so Size is the ArgCount
319 // for the next element. The recursion stops when Sizes is empty for the last element.
320 //
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800321 template <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
322 std::size_t Size, std::size_t... Sizes, typename... Args>
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700323 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
324 std::index_sequence<Size, Sizes...>, std::tuple<Args...>& tuple)
325 : StaticVector(std::index_sequence<I + 1, ArgIndex + ArgCount, Size>{},
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800326 std::make_index_sequence<Size>{}, std::index_sequence<Sizes...>{},
327 tuple) {
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700328 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
329 }
330
331 // Base case for in-place constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800332 template <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
333 typename... Args>
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700334 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
335 std::index_sequence<>, std::tuple<Args...>& tuple)
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800336 : size_(I + 1) {
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700337 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
338 }
339
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800340 size_type size_ = 0;
341 std::aligned_storage_t<sizeof(value_type), alignof(value_type)> data_[N];
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700342};
343
344// Deduction guide for array constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800345template <typename T, std::size_t N>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700346StaticVector(T (&)[N]) -> StaticVector<std::remove_cv_t<T>, N>;
347
348// Deduction guide for variadic constructor.
349template <typename T, typename... Us, typename V = std::decay_t<T>,
350 typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>>
351StaticVector(T&&, Us&&...) -> StaticVector<V, 1 + sizeof...(Us)>;
352
353// Deduction guide for in-place constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800354template <typename T, std::size_t... Sizes, typename... Types>
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700355StaticVector(InitializerList<T, std::index_sequence<Sizes...>, Types...>&&)
356 -> StaticVector<T, sizeof...(Sizes)>;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700357
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800358template <typename T, std::size_t N>
359template <bool IsEmpty>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700360void StaticVector<T, N>::swap(StaticVector& other) {
361 auto [to, from] = std::make_pair(this, &other);
362 if (from == this) return;
363
364 // Assume this vector has fewer elements, so the excess of the other vector will be moved to it.
365 auto [min, max] = std::make_pair(size(), other.size());
366
367 // No elements to swap if moving into an empty vector.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800368 if constexpr (IsEmpty) {
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700369 assert(min == 0);
370 } else {
371 if (min > max) {
372 std::swap(from, to);
373 std::swap(min, max);
374 }
375
376 // Swap elements [0, min).
377 std::swap_ranges(begin(), begin() + min, other.begin());
378
379 // No elements to move if sizes are equal.
380 if (min == max) return;
381 }
382
383 // Move elements [min, max) and destroy their source for destructor side effects.
384 const auto [first, last] = std::make_pair(from->begin() + min, from->begin() + max);
385 std::uninitialized_move(first, last, to->begin() + min);
386 std::destroy(first, last);
387
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800388 std::swap(size_, other.size_);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700389}
390
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800391template <typename T, std::size_t N>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700392inline void swap(StaticVector<T, N>& lhs, StaticVector<T, N>& rhs) {
393 lhs.swap(rhs);
394}
395
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700396} // namespace android::ftl