blob: eb83b85bfe7f5295c26f465ae11fdcea008f0595 [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 Laskowski04667b72021-12-15 13:14:54 -080019#include <ftl/details/array_traits.h>
Dominik Laskowski5444fc82020-11-24 13:41:10 -080020#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 Laskowskie21dbed2020-12-04 20:51:43 -080031constexpr struct IteratorRangeTag {
32} kIteratorRange;
Dominik Laskowski03572372020-10-27 22:36:00 -070033
Dominik Laskowski5444fc82020-11-24 13:41:10 -080034// Fixed-capacity, statically allocated counterpart of std::vector. Like std::array, StaticVector
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070035// allocates contiguous storage for N elements of type T at compile time, but stores at most (rather
36// than exactly) N elements. Unlike std::array, its default constructor does not require T to have a
Dominik Laskowskiccd50a42020-10-30 19:56:38 -070037// default constructor, since elements are constructed in place as the vector grows. Operations that
Dominik Laskowski03572372020-10-27 22:36:00 -070038// insert an element (emplace_back, push_back, etc.) fail when the vector is full. The API otherwise
39// adheres to standard containers, except the unstable_erase operation that does not preserve order,
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070040// and the replace operation that destructively emplaces.
41//
Dominik Laskowski206996f2022-01-20 13:21:57 -080042// Unlike std::vector, T does not require copy/move assignment, so may be an object with const data
43// members, or be const itself.
44//
Dominik Laskowski5444fc82020-11-24 13:41:10 -080045// StaticVector<T, 1> is analogous to an iterable std::optional.
46// StaticVector<T, 0> is an error.
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070047//
48// Example usage:
49//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080050// ftl::StaticVector<char, 3> vector;
51// assert(vector.empty());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070052//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080053// vector = {'a', 'b'};
54// assert(vector.size() == 2u);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070055//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080056// vector.push_back('c');
57// assert(vector.full());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070058//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080059// assert(!vector.push_back('d'));
60// assert(vector.size() == 3u);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070061//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080062// vector.unstable_erase(vector.begin());
63// assert(vector == (ftl::StaticVector{'c', 'b'}));
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070064//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080065// vector.pop_back();
66// assert(vector.back() == 'c');
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070067//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080068// const char array[] = "hi";
69// vector = ftl::StaticVector(array);
70// assert(vector == (ftl::StaticVector{'h', 'i', '\0'}));
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070071//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080072// ftl::StaticVector strings = ftl::init::list<std::string>("abc")("123456", 3u)(3u, '?');
73// assert(strings.size() == 3u);
74// assert(strings[0] == "abc");
75// assert(strings[1] == "123");
76// assert(strings[2] == "???");
Dominik Laskowskiccd50a42020-10-30 19:56:38 -070077//
Dominik Laskowski5444fc82020-11-24 13:41:10 -080078template <typename T, std::size_t N>
Dominik Laskowski04667b72021-12-15 13:14:54 -080079class StaticVector final : details::ArrayTraits<T>,
80 details::ArrayIterators<StaticVector<T, N>, T>,
81 details::ArrayComparators<StaticVector> {
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080082 static_assert(N > 0);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070083
Dominik Laskowski206996f2022-01-20 13:21:57 -080084 // For constructor that moves from a smaller convertible vector.
85 template <typename, std::size_t>
86 friend class StaticVector;
87
Dominik Laskowski04667b72021-12-15 13:14:54 -080088 using details::ArrayTraits<T>::construct_at;
Dominik Laskowski206996f2022-01-20 13:21:57 -080089 using details::ArrayTraits<T>::replace_at;
90 using details::ArrayTraits<T>::in_place_swap_ranges;
91 using details::ArrayTraits<T>::uninitialized_copy;
Dominik Laskowski0bacf272020-10-22 14:08:27 -070092
Dominik Laskowski04667b72021-12-15 13:14:54 -080093 using Iter = details::ArrayIterators<StaticVector, T>;
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080094 friend Iter;
Dominik Laskowski0bacf272020-10-22 14:08:27 -070095
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080096 // There is ambiguity when constructing from two iterator-like elements like pointers:
97 // they could be an iterator range, or arguments for in-place construction. Assume the
98 // latter unless they are input iterators and cannot be used to construct elements. If
99 // the former is intended, the caller can pass an IteratorRangeTag to disambiguate.
100 template <typename I, typename Traits = std::iterator_traits<I>>
101 using is_input_iterator =
102 std::conjunction<std::is_base_of<std::input_iterator_tag, typename Traits::iterator_category>,
103 std::negation<std::is_constructible<T, I>>>;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700104
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800105 public:
106 FTL_ARRAY_TRAIT(T, value_type);
107 FTL_ARRAY_TRAIT(T, size_type);
108 FTL_ARRAY_TRAIT(T, difference_type);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700109
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800110 FTL_ARRAY_TRAIT(T, pointer);
111 FTL_ARRAY_TRAIT(T, reference);
112 FTL_ARRAY_TRAIT(T, iterator);
113 FTL_ARRAY_TRAIT(T, reverse_iterator);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700114
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800115 FTL_ARRAY_TRAIT(T, const_pointer);
116 FTL_ARRAY_TRAIT(T, const_reference);
117 FTL_ARRAY_TRAIT(T, const_iterator);
118 FTL_ARRAY_TRAIT(T, const_reverse_iterator);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700119
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800120 // Creates an empty vector.
121 StaticVector() = default;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700122
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800123 // Copies and moves a vector, respectively.
124 StaticVector(const StaticVector& other)
125 : StaticVector(kIteratorRange, other.begin(), other.end()) {}
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800126
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800127 StaticVector(StaticVector&& other) { swap<true>(other); }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700128
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800129 // Copies at most N elements from a smaller convertible vector.
Dominik Laskowski206996f2022-01-20 13:21:57 -0800130 template <typename U, std::size_t M>
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800131 StaticVector(const StaticVector<U, M>& other)
Dominik Laskowski206996f2022-01-20 13:21:57 -0800132 : StaticVector(kIteratorRange, other.begin(), other.end()) {
133 static_assert(N >= M, "Insufficient capacity");
134 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700135
Dominik Laskowski206996f2022-01-20 13:21:57 -0800136 // Copies at most N elements from a smaller convertible array.
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800137 template <typename U, std::size_t M>
138 explicit StaticVector(U (&array)[M])
Dominik Laskowski206996f2022-01-20 13:21:57 -0800139 : StaticVector(kIteratorRange, std::begin(array), std::end(array)) {
140 static_assert(N >= M, "Insufficient capacity");
141 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700142
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800143 // Copies at most N elements from the range [first, last).
144 //
145 // IteratorRangeTag disambiguates with initialization from two iterator-like elements.
146 //
147 template <typename Iterator, typename = std::enable_if_t<is_input_iterator<Iterator>{}>>
148 StaticVector(Iterator first, Iterator last) : StaticVector(kIteratorRange, first, last) {
149 using V = typename std::iterator_traits<Iterator>::value_type;
150 static_assert(std::is_constructible_v<value_type, V>, "Incompatible iterator range");
151 }
152
153 template <typename Iterator>
154 StaticVector(IteratorRangeTag, Iterator first, Iterator last)
155 : size_(std::min(max_size(), static_cast<size_type>(std::distance(first, last)))) {
Dominik Laskowski206996f2022-01-20 13:21:57 -0800156 uninitialized_copy(first, first + size_, begin());
157 }
158
159 // Moves at most N elements from a smaller convertible vector.
160 template <typename U, std::size_t M>
161 StaticVector(StaticVector<U, M>&& other) {
162 static_assert(N >= M, "Insufficient capacity");
163
164 // Same logic as swap<true>, though M need not be equal to N.
165 std::uninitialized_move(other.begin(), other.end(), begin());
166 std::destroy(other.begin(), other.end());
167 std::swap(size_, other.size_);
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800168 }
169
170 // Constructs at most N elements. The template arguments T and N are inferred using the
171 // deduction guide defined below. Note that T is determined from the first element, and
172 // subsequent elements must have convertible types:
173 //
174 // ftl::StaticVector vector = {1, 2, 3};
175 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<int, 3>>);
176 //
177 // const auto copy = "quince"s;
178 // auto move = "tart"s;
179 // ftl::StaticVector vector = {copy, std::move(move)};
180 //
181 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 2>>);
182 //
183 template <typename E, typename... Es,
184 typename = std::enable_if_t<std::is_constructible_v<value_type, E>>>
185 StaticVector(E&& element, Es&&... elements)
186 : StaticVector(std::index_sequence<0>{}, std::forward<E>(element),
187 std::forward<Es>(elements)...) {
188 static_assert(sizeof...(elements) < N, "Too many elements");
189 }
190
191 // Constructs at most N elements in place by forwarding per-element constructor arguments. The
192 // template arguments T and N are inferred using the deduction guide defined below. The syntax
193 // for listing arguments is as follows:
194 //
195 // ftl::StaticVector vector = ftl::init::list<std::string>("abc")()(3u, '?');
196 //
197 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 3>>);
198 // assert(vector.full());
199 // assert(vector[0] == "abc");
200 // assert(vector[1].empty());
201 // assert(vector[2] == "???");
202 //
203 template <typename U, std::size_t Size, std::size_t... Sizes, typename... Types>
204 StaticVector(InitializerList<U, std::index_sequence<Size, Sizes...>, Types...>&& list)
205 : StaticVector(std::index_sequence<0, 0, Size>{}, std::make_index_sequence<Size>{},
Dominik Laskowski17f6b972022-01-25 13:41:52 -0800206 std::index_sequence<Sizes...>{}, list.tuple) {
207 static_assert(sizeof...(Sizes) < N, "Too many elements");
208 }
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800209
210 ~StaticVector() { std::destroy(begin(), end()); }
211
212 StaticVector& operator=(const StaticVector& other) {
213 StaticVector copy(other);
214 swap(copy);
215 return *this;
216 }
217
218 StaticVector& operator=(StaticVector&& other) {
Dominik Laskowski44828ce2021-09-13 11:00:22 -0700219 clear();
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800220 swap<true>(other);
221 return *this;
222 }
223
224 // IsEmpty enables a fast path when the vector is known to be empty at compile time.
225 template <bool IsEmpty = false>
226 void swap(StaticVector&);
227
228 static constexpr size_type max_size() { return N; }
229 size_type size() const { return size_; }
230
231 bool empty() const { return size() == 0; }
232 bool full() const { return size() == max_size(); }
233
234 iterator begin() { return std::launder(reinterpret_cast<pointer>(data_)); }
235 iterator end() { return begin() + size(); }
236
237 using Iter::begin;
238 using Iter::end;
239
240 using Iter::cbegin;
241 using Iter::cend;
242
243 using Iter::rbegin;
244 using Iter::rend;
245
246 using Iter::crbegin;
247 using Iter::crend;
248
249 using Iter::last;
250
251 using Iter::back;
252 using Iter::front;
253
254 using Iter::operator[];
255
256 // Replaces an element, and returns a reference to it. The iterator must be dereferenceable, so
257 // replacing at end() is erroneous.
258 //
259 // The element is emplaced via move constructor, so type T does not need to define copy/move
260 // assignment, e.g. its data members may be const.
261 //
262 // The arguments may directly or indirectly refer to the element being replaced.
263 //
264 // Iterators to the replaced element point to its replacement, and others remain valid.
265 //
266 template <typename... Args>
267 reference replace(const_iterator it, Args&&... args) {
Dominik Laskowski206996f2022-01-20 13:21:57 -0800268 return replace_at(it, std::forward<Args>(args)...);
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800269 }
270
271 // Appends an element, and returns an iterator to it. If the vector is full, the element is not
272 // inserted, and the end() iterator is returned.
273 //
274 // On success, the end() iterator is invalidated.
275 //
276 template <typename... Args>
277 iterator emplace_back(Args&&... args) {
278 if (full()) return end();
279 const iterator it = construct_at(end(), std::forward<Args>(args)...);
280 ++size_;
281 return it;
282 }
283
284 // Appends an element unless the vector is full, and returns whether the element was inserted.
285 //
286 // On success, the end() iterator is invalidated.
287 //
288 bool push_back(const value_type& v) {
289 // Two statements for sequence point.
290 const iterator it = emplace_back(v);
291 return it != end();
292 }
293
294 bool push_back(value_type&& v) {
295 // Two statements for sequence point.
296 const iterator it = emplace_back(std::move(v));
297 return it != end();
298 }
299
300 // Removes the last element. The vector must not be empty, or the call is erroneous.
301 //
302 // The last() and end() iterators are invalidated.
303 //
304 void pop_back() { unstable_erase(last()); }
305
Dominik Laskowski44828ce2021-09-13 11:00:22 -0700306 // Removes all elements.
307 //
308 // All iterators are invalidated.
309 //
310 void clear() {
311 std::destroy(begin(), end());
312 size_ = 0;
313 }
314
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800315 // Erases an element, but does not preserve order. Rather than shifting subsequent elements,
316 // this moves the last element to the slot of the erased element.
317 //
318 // The last() and end() iterators, as well as those to the erased element, are invalidated.
319 //
320 void unstable_erase(const_iterator it) {
321 std::destroy_at(it);
322 if (it != last()) {
323 // Move last element and destroy its source for destructor side effects. This is only
324 // safe because exceptions are disabled.
325 construct_at(it, std::move(back()));
326 std::destroy_at(last());
Dominik Laskowski03572372020-10-27 22:36:00 -0700327 }
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800328 --size_;
329 }
Dominik Laskowski03572372020-10-27 22:36:00 -0700330
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800331 private:
332 // Recursion for variadic constructor.
333 template <std::size_t I, typename E, typename... Es>
334 StaticVector(std::index_sequence<I>, E&& element, Es&&... elements)
335 : StaticVector(std::index_sequence<I + 1>{}, std::forward<Es>(elements)...) {
336 construct_at(begin() + I, std::forward<E>(element));
337 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700338
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800339 // Base case for variadic constructor.
340 template <std::size_t I>
341 explicit StaticVector(std::index_sequence<I>) : size_(I) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700342
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800343 // Recursion for in-place constructor.
344 //
345 // Construct element I by extracting its arguments from the InitializerList tuple. ArgIndex
346 // is the position of its first argument in Args, and ArgCount is the number of arguments.
347 // The Indices sequence corresponds to [0, ArgCount).
348 //
349 // The Sizes sequence lists the argument counts for elements after I, so Size is the ArgCount
350 // for the next element. The recursion stops when Sizes is empty for the last element.
351 //
352 template <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
353 std::size_t Size, std::size_t... Sizes, typename... Args>
354 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
355 std::index_sequence<Size, Sizes...>, std::tuple<Args...>& tuple)
356 : StaticVector(std::index_sequence<I + 1, ArgIndex + ArgCount, Size>{},
357 std::make_index_sequence<Size>{}, std::index_sequence<Sizes...>{}, tuple) {
358 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
359 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700360
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800361 // Base case for in-place constructor.
362 template <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
363 typename... Args>
364 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
365 std::index_sequence<>, std::tuple<Args...>& tuple)
366 : size_(I + 1) {
367 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
368 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700369
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800370 size_type size_ = 0;
371 std::aligned_storage_t<sizeof(value_type), alignof(value_type)> data_[N];
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700372};
373
374// Deduction guide for array constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800375template <typename T, std::size_t N>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700376StaticVector(T (&)[N]) -> StaticVector<std::remove_cv_t<T>, N>;
377
378// Deduction guide for variadic constructor.
379template <typename T, typename... Us, typename V = std::decay_t<T>,
380 typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>>
381StaticVector(T&&, Us&&...) -> StaticVector<V, 1 + sizeof...(Us)>;
382
383// Deduction guide for in-place constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800384template <typename T, std::size_t... Sizes, typename... Types>
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700385StaticVector(InitializerList<T, std::index_sequence<Sizes...>, Types...>&&)
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800386 -> StaticVector<T, sizeof...(Sizes)>;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700387
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800388template <typename T, std::size_t N>
389template <bool IsEmpty>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700390void StaticVector<T, N>::swap(StaticVector& other) {
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800391 auto [to, from] = std::make_pair(this, &other);
392 if (from == this) return;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700393
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800394 // Assume this vector has fewer elements, so the excess of the other vector will be moved to it.
395 auto [min, max] = std::make_pair(size(), other.size());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700396
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800397 // No elements to swap if moving into an empty vector.
398 if constexpr (IsEmpty) {
399 assert(min == 0);
400 } else {
401 if (min > max) {
402 std::swap(from, to);
403 std::swap(min, max);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700404 }
405
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800406 // Swap elements [0, min).
Dominik Laskowski206996f2022-01-20 13:21:57 -0800407 in_place_swap_ranges(begin(), begin() + min, other.begin());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700408
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800409 // No elements to move if sizes are equal.
410 if (min == max) return;
411 }
412
413 // Move elements [min, max) and destroy their source for destructor side effects.
414 const auto [first, last] = std::make_pair(from->begin() + min, from->begin() + max);
415 std::uninitialized_move(first, last, to->begin() + min);
416 std::destroy(first, last);
417
418 std::swap(size_, other.size_);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700419}
420
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800421template <typename T, std::size_t N>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700422inline void swap(StaticVector<T, N>& lhs, StaticVector<T, N>& rhs) {
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800423 lhs.swap(rhs);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700424}
425
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800426} // namespace android::ftl