blob: c1325568a02d6ebae90ce088d7f442f968740b27 [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 Laskowski0bacf272020-10-22 14:08:27 -070019#include <ftl/ArrayTraits.h>
Dominik Laskowskiccd50a42020-10-30 19:56:38 -070020#include <ftl/InitializerList.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 Laskowski03572372020-10-27 22:36:00 -070031constexpr struct IteratorRangeTag {} IteratorRange;
32
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070033// Fixed-capacity, statically allocated counterpart of std::vector. Akin to std::array, StaticVector
34// 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//
41// StaticVector<T, 1> is analogous to an iterable std::optional, but StaticVector<T, 0> is an error.
42//
43// Example usage:
44//
45// ftl::StaticVector<char, 3> vector;
46// assert(vector.empty());
47//
48// vector = {'a', 'b'};
49// assert(vector.size() == 2u);
50//
51// vector.push_back('c');
52// assert(vector.full());
53//
54// assert(!vector.push_back('d'));
55// assert(vector.size() == 3u);
56//
57// vector.unstable_erase(vector.begin());
58// assert(vector == (ftl::StaticVector{'c', 'b'}));
59//
60// vector.pop_back();
61// assert(vector.back() == 'c');
62//
63// const char array[] = "hi";
64// vector = ftl::StaticVector(array);
65// assert(vector == (ftl::StaticVector{'h', 'i', '\0'}));
66//
Dominik Laskowskiccd50a42020-10-30 19:56:38 -070067// ftl::StaticVector strings = ftl::init::list<std::string>("abc")
68// ("123456", 3u)
69// (3u, '?');
70// assert(strings.size() == 3u);
71// assert(strings[0] == "abc");
72// assert(strings[1] == "123");
73// assert(strings[2] == "???");
74//
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070075template <typename T, size_t N>
Dominik Laskowski0bacf272020-10-22 14:08:27 -070076class StaticVector final : ArrayTraits<T>,
77 ArrayIterators<StaticVector<T, N>, T>,
78 ArrayComparators<StaticVector> {
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070079 static_assert(N > 0);
80
Dominik Laskowski0bacf272020-10-22 14:08:27 -070081 using ArrayTraits<T>::construct_at;
82
83 using Iter = ArrayIterators<StaticVector, T>;
84 friend Iter;
85
Dominik Laskowski03572372020-10-27 22:36:00 -070086 // There is ambiguity when constructing from two iterator-like elements like pointers:
87 // they could be an iterator range, or arguments for in-place construction. Assume the
88 // latter unless they are input iterators and cannot be used to construct elements. If
89 // the former is intended, the caller can pass an IteratorRangeTag to disambiguate.
90 template <typename I, typename Traits = std::iterator_traits<I>>
91 using IsInputIterator = std::conjunction<
92 std::is_base_of<std::input_iterator_tag, typename Traits::iterator_category>,
93 std::negation<std::is_constructible<T, I>>>;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070094
95public:
Dominik Laskowski0bacf272020-10-22 14:08:27 -070096 FTL_ARRAY_TRAIT(T, value_type);
97 FTL_ARRAY_TRAIT(T, size_type);
98 FTL_ARRAY_TRAIT(T, difference_type);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070099
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700100 FTL_ARRAY_TRAIT(T, pointer);
101 FTL_ARRAY_TRAIT(T, reference);
102 FTL_ARRAY_TRAIT(T, iterator);
103 FTL_ARRAY_TRAIT(T, reverse_iterator);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700104
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700105 FTL_ARRAY_TRAIT(T, const_pointer);
106 FTL_ARRAY_TRAIT(T, const_reference);
107 FTL_ARRAY_TRAIT(T, const_iterator);
108 FTL_ARRAY_TRAIT(T, const_reverse_iterator);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700109
110 // Creates an empty vector.
111 StaticVector() = default;
112
113 // Copies and moves a vector, respectively.
Dominik Laskowski03572372020-10-27 22:36:00 -0700114 StaticVector(const StaticVector& other)
115 : StaticVector(IteratorRange, other.begin(), other.end()) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700116 StaticVector(StaticVector&& other) { swap<Empty>(other); }
117
118 // Copies at most N elements from a smaller convertible vector.
119 template <typename U, size_t M, typename = std::enable_if_t<M <= N>>
Dominik Laskowski03572372020-10-27 22:36:00 -0700120 StaticVector(const StaticVector<U, M>& other)
121 : StaticVector(IteratorRange, other.begin(), other.end()) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700122
123 // Copies at most N elements from an array.
124 template <typename U, size_t M>
Dominik Laskowski03572372020-10-27 22:36:00 -0700125 explicit StaticVector(U (&array)[M])
126 : StaticVector(IteratorRange, std::begin(array), std::end(array)) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700127
128 // Copies at most N elements from the range [first, last).
Dominik Laskowski03572372020-10-27 22:36:00 -0700129 //
130 // IteratorRangeTag disambiguates with initialization from two iterator-like elements.
131 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700132 template <typename Iterator, typename = std::enable_if_t<IsInputIterator<Iterator>{}>>
Dominik Laskowski03572372020-10-27 22:36:00 -0700133 StaticVector(Iterator first, Iterator last) : StaticVector(IteratorRange, first, last) {
134 using V = typename std::iterator_traits<Iterator>::value_type;
135 static_assert(std::is_constructible_v<value_type, V>, "Incompatible iterator range");
136 }
137
138 template <typename Iterator>
139 StaticVector(IteratorRangeTag, Iterator first, Iterator last)
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700140 : mSize(std::min(max_size(), static_cast<size_type>(std::distance(first, last)))) {
141 std::uninitialized_copy(first, first + mSize, begin());
142 }
143
144 // Constructs at most N elements. The template arguments T and N are inferred using the
145 // deduction guide defined below. Note that T is determined from the first element, and
146 // subsequent elements must have convertible types:
147 //
148 // ftl::StaticVector vector = {1, 2, 3};
149 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<int, 3>>);
150 //
151 // const auto copy = "quince"s;
152 // auto move = "tart"s;
153 // ftl::StaticVector vector = {copy, std::move(move)};
154 //
155 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 2>>);
156 //
157 template <typename E, typename... Es,
158 typename = std::enable_if_t<std::is_constructible_v<value_type, E>>>
159 StaticVector(E&& element, Es&&... elements)
160 : StaticVector(std::index_sequence<0>{}, std::forward<E>(element),
161 std::forward<Es>(elements)...) {
162 static_assert(sizeof...(elements) < N, "Too many elements");
163 }
164
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700165 // Constructs at most N elements in place by forwarding per-element constructor arguments. The
166 // template arguments T and N are inferred using the deduction guide defined below. The syntax
167 // for listing arguments is as follows:
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700168 //
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700169 // ftl::StaticVector vector = ftl::init::list<std::string>("abc")()(3u, '?');
170 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700171 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 3>>);
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700172 // assert(vector.full());
173 // assert(vector[0] == "abc");
174 // assert(vector[1].empty());
175 // assert(vector[2] == "???");
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700176 //
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700177 template <typename U, size_t Size, size_t... Sizes, typename... Types>
178 StaticVector(InitializerList<U, std::index_sequence<Size, Sizes...>, Types...>&& init)
179 : StaticVector(std::index_sequence<0, 0, Size>{}, std::make_index_sequence<Size>{},
180 std::index_sequence<Sizes...>{}, init.tuple) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700181
182 ~StaticVector() { std::destroy(begin(), end()); }
183
184 StaticVector& operator=(const StaticVector& other) {
185 StaticVector copy(other);
186 swap(copy);
187 return *this;
188 }
189
190 StaticVector& operator=(StaticVector&& other) {
191 std::destroy(begin(), end());
192 mSize = 0;
193 swap<Empty>(other);
194 return *this;
195 }
196
197 template <typename = void>
198 void swap(StaticVector&);
199
Dominik Laskowski03572372020-10-27 22:36:00 -0700200 static constexpr size_type max_size() { return N; }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700201 size_type size() const { return mSize; }
202
203 bool empty() const { return size() == 0; }
204 bool full() const { return size() == max_size(); }
205
206 iterator begin() { return std::launder(reinterpret_cast<pointer>(mData)); }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700207 iterator end() { return begin() + size(); }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700208
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700209 using Iter::begin;
210 using Iter::end;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700211
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700212 using Iter::cbegin;
213 using Iter::cend;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700214
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700215 using Iter::rbegin;
216 using Iter::rend;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700217
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700218 using Iter::crbegin;
219 using Iter::crend;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700220
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700221 using Iter::last;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700222
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700223 using Iter::back;
224 using Iter::front;
225
226 using Iter::operator[];
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700227
Dominik Laskowski03572372020-10-27 22:36:00 -0700228 // Replaces an element, and returns a reference to it. The iterator must be dereferenceable, so
229 // replacing at end() is erroneous.
230 //
231 // The element is emplaced via move constructor, so type T does not need to define copy/move
232 // assignment, e.g. its data members may be const.
233 //
234 // The arguments may directly or indirectly refer to the element being replaced.
235 //
236 // Iterators to the replaced element point to its replacement, and others remain valid.
237 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700238 template <typename... Args>
Dominik Laskowski03572372020-10-27 22:36:00 -0700239 reference replace(const_iterator it, Args&&... args) {
240 value_type element{std::forward<Args>(args)...};
241 std::destroy_at(it);
242 // This is only safe because exceptions are disabled.
243 return *construct_at(it, std::move(element));
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700244 }
245
246 // 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 -0700247 // inserted, and the end() iterator is returned.
248 //
249 // On success, the end() iterator is invalidated.
250 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700251 template <typename... Args>
252 iterator emplace_back(Args&&... args) {
253 if (full()) return end();
254 const iterator it = construct_at(end(), std::forward<Args>(args)...);
255 ++mSize;
256 return it;
257 }
258
Dominik Laskowski03572372020-10-27 22:36:00 -0700259 // Appends an element unless the vector is full, and returns whether the element was inserted.
260 //
261 // On success, the end() iterator is invalidated.
262 //
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700263 bool push_back(const value_type& v) {
264 // Two statements for sequence point.
265 const iterator it = emplace_back(v);
266 return it != end();
267 }
268
269 bool push_back(value_type&& v) {
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700270 // Two statements for sequence point.
271 const iterator it = emplace_back(std::move(v));
272 return it != end();
273 }
274
Dominik Laskowski03572372020-10-27 22:36:00 -0700275 // Removes the last element. The vector must not be empty, or the call is erroneous.
276 //
277 // The last() and end() iterators are invalidated.
278 //
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700279 void pop_back() { unstable_erase(last()); }
280
Dominik Laskowski03572372020-10-27 22:36:00 -0700281 // Erases an element, but does not preserve order. Rather than shifting subsequent elements,
282 // this moves the last element to the slot of the erased element.
283 //
284 // The last() and end() iterators, as well as those to the erased element, are invalidated.
285 //
286 void unstable_erase(const_iterator it) {
287 std::destroy_at(it);
288 if (it != last()) {
289 // Move last element and destroy its source for destructor side effects. This is only
290 // safe because exceptions are disabled.
291 construct_at(it, std::move(back()));
292 std::destroy_at(last());
293 }
294 --mSize;
295 }
296
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700297private:
298 struct Empty {};
299
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700300 // Recursion for variadic constructor.
301 template <size_t I, typename E, typename... Es>
302 StaticVector(std::index_sequence<I>, E&& element, Es&&... elements)
303 : StaticVector(std::index_sequence<I + 1>{}, std::forward<Es>(elements)...) {
304 construct_at(begin() + I, std::forward<E>(element));
305 }
306
307 // Base case for variadic constructor.
308 template <size_t I>
309 explicit StaticVector(std::index_sequence<I>) : mSize(I) {}
310
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700311 // Recursion for in-place constructor.
312 //
313 // Construct element I by extracting its arguments from the InitializerList tuple. ArgIndex
314 // is the position of its first argument in Args, and ArgCount is the number of arguments.
315 // The Indices sequence corresponds to [0, ArgCount).
316 //
317 // The Sizes sequence lists the argument counts for elements after I, so Size is the ArgCount
318 // for the next element. The recursion stops when Sizes is empty for the last element.
319 //
320 template <size_t I, size_t ArgIndex, size_t ArgCount, size_t... Indices, size_t Size,
321 size_t... Sizes, typename... Args>
322 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
323 std::index_sequence<Size, Sizes...>, std::tuple<Args...>& tuple)
324 : StaticVector(std::index_sequence<I + 1, ArgIndex + ArgCount, Size>{},
325 std::make_index_sequence<Size>{}, std::index_sequence<Sizes...>{}, tuple) {
326 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
327 }
328
329 // Base case for in-place constructor.
330 template <size_t I, size_t ArgIndex, size_t ArgCount, size_t... Indices, typename... Args>
331 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
332 std::index_sequence<>, std::tuple<Args...>& tuple)
333 : mSize(I + 1) {
334 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
335 }
336
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700337 size_type mSize = 0;
338 std::aligned_storage_t<sizeof(value_type), alignof(value_type)> mData[N];
339};
340
341// Deduction guide for array constructor.
342template <typename T, size_t N>
343StaticVector(T (&)[N]) -> StaticVector<std::remove_cv_t<T>, N>;
344
345// Deduction guide for variadic constructor.
346template <typename T, typename... Us, typename V = std::decay_t<T>,
347 typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>>
348StaticVector(T&&, Us&&...) -> StaticVector<V, 1 + sizeof...(Us)>;
349
350// Deduction guide for in-place constructor.
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700351template <typename T, size_t... Sizes, typename... Types>
352StaticVector(InitializerList<T, std::index_sequence<Sizes...>, Types...>&&)
353 -> StaticVector<T, sizeof...(Sizes)>;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700354
355template <typename T, size_t N>
356template <typename E>
357void StaticVector<T, N>::swap(StaticVector& other) {
358 auto [to, from] = std::make_pair(this, &other);
359 if (from == this) return;
360
361 // Assume this vector has fewer elements, so the excess of the other vector will be moved to it.
362 auto [min, max] = std::make_pair(size(), other.size());
363
364 // No elements to swap if moving into an empty vector.
365 if constexpr (std::is_same_v<E, Empty>) {
366 assert(min == 0);
367 } else {
368 if (min > max) {
369 std::swap(from, to);
370 std::swap(min, max);
371 }
372
373 // Swap elements [0, min).
374 std::swap_ranges(begin(), begin() + min, other.begin());
375
376 // No elements to move if sizes are equal.
377 if (min == max) return;
378 }
379
380 // Move elements [min, max) and destroy their source for destructor side effects.
381 const auto [first, last] = std::make_pair(from->begin() + min, from->begin() + max);
382 std::uninitialized_move(first, last, to->begin() + min);
383 std::destroy(first, last);
384
385 std::swap(mSize, other.mSize);
386}
387
388template <typename T, size_t N>
389inline void swap(StaticVector<T, N>& lhs, StaticVector<T, N>& rhs) {
390 lhs.swap(rhs);
391}
392
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700393} // namespace android::ftl