blob: 70f1721d4a228670f997fad7dfb6b7ab8f6633f1 [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 Laskowski5444fc82020-11-24 13:41:10 -080042// StaticVector<T, 1> is analogous to an iterable std::optional.
43// StaticVector<T, 0> is an error.
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070044//
45// Example usage:
46//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080047// ftl::StaticVector<char, 3> vector;
48// assert(vector.empty());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070049//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080050// vector = {'a', 'b'};
51// assert(vector.size() == 2u);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070052//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080053// vector.push_back('c');
54// assert(vector.full());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070055//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080056// assert(!vector.push_back('d'));
57// assert(vector.size() == 3u);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070058//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080059// vector.unstable_erase(vector.begin());
60// assert(vector == (ftl::StaticVector{'c', 'b'}));
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070061//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080062// vector.pop_back();
63// assert(vector.back() == 'c');
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070064//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080065// const char array[] = "hi";
66// vector = ftl::StaticVector(array);
67// assert(vector == (ftl::StaticVector{'h', 'i', '\0'}));
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070068//
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080069// ftl::StaticVector strings = ftl::init::list<std::string>("abc")("123456", 3u)(3u, '?');
70// assert(strings.size() == 3u);
71// assert(strings[0] == "abc");
72// assert(strings[1] == "123");
73// assert(strings[2] == "???");
Dominik Laskowskiccd50a42020-10-30 19:56:38 -070074//
Dominik Laskowski5444fc82020-11-24 13:41:10 -080075template <typename T, std::size_t N>
Dominik Laskowski04667b72021-12-15 13:14:54 -080076class StaticVector final : details::ArrayTraits<T>,
77 details::ArrayIterators<StaticVector<T, N>, T>,
78 details::ArrayComparators<StaticVector> {
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080079 static_assert(N > 0);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -070080
Dominik Laskowski04667b72021-12-15 13:14:54 -080081 using details::ArrayTraits<T>::construct_at;
Dominik Laskowski0bacf272020-10-22 14:08:27 -070082
Dominik Laskowski04667b72021-12-15 13:14:54 -080083 using Iter = details::ArrayIterators<StaticVector, T>;
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080084 friend Iter;
Dominik Laskowski0bacf272020-10-22 14:08:27 -070085
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080086 // 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 is_input_iterator =
92 std::conjunction<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
Dominik Laskowskie21dbed2020-12-04 20:51:43 -080095 public:
96 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 Laskowskie21dbed2020-12-04 20:51:43 -0800100 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 Laskowskie21dbed2020-12-04 20:51:43 -0800105 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
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800110 // Creates an empty vector.
111 StaticVector() = default;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700112
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800113 // Copies and moves a vector, respectively.
114 StaticVector(const StaticVector& other)
115 : StaticVector(kIteratorRange, other.begin(), other.end()) {}
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800116
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800117 StaticVector(StaticVector&& other) { swap<true>(other); }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700118
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800119 // Copies at most N elements from a smaller convertible vector.
120 template <typename U, std::size_t M, typename = std::enable_if_t<M <= N>>
121 StaticVector(const StaticVector<U, M>& other)
122 : StaticVector(kIteratorRange, other.begin(), other.end()) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700123
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800124 // Copies at most N elements from an array.
125 template <typename U, std::size_t M>
126 explicit StaticVector(U (&array)[M])
127 : StaticVector(kIteratorRange, std::begin(array), std::end(array)) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700128
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800129 // Copies at most N elements from the range [first, last).
130 //
131 // IteratorRangeTag disambiguates with initialization from two iterator-like elements.
132 //
133 template <typename Iterator, typename = std::enable_if_t<is_input_iterator<Iterator>{}>>
134 StaticVector(Iterator first, Iterator last) : StaticVector(kIteratorRange, first, last) {
135 using V = typename std::iterator_traits<Iterator>::value_type;
136 static_assert(std::is_constructible_v<value_type, V>, "Incompatible iterator range");
137 }
138
139 template <typename Iterator>
140 StaticVector(IteratorRangeTag, Iterator first, Iterator last)
141 : size_(std::min(max_size(), static_cast<size_type>(std::distance(first, last)))) {
142 std::uninitialized_copy(first, first + size_, begin());
143 }
144
145 // Constructs at most N elements. The template arguments T and N are inferred using the
146 // deduction guide defined below. Note that T is determined from the first element, and
147 // subsequent elements must have convertible types:
148 //
149 // ftl::StaticVector vector = {1, 2, 3};
150 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<int, 3>>);
151 //
152 // const auto copy = "quince"s;
153 // auto move = "tart"s;
154 // ftl::StaticVector vector = {copy, std::move(move)};
155 //
156 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 2>>);
157 //
158 template <typename E, typename... Es,
159 typename = std::enable_if_t<std::is_constructible_v<value_type, E>>>
160 StaticVector(E&& element, Es&&... elements)
161 : StaticVector(std::index_sequence<0>{}, std::forward<E>(element),
162 std::forward<Es>(elements)...) {
163 static_assert(sizeof...(elements) < N, "Too many elements");
164 }
165
166 // Constructs at most N elements in place by forwarding per-element constructor arguments. The
167 // template arguments T and N are inferred using the deduction guide defined below. The syntax
168 // for listing arguments is as follows:
169 //
170 // ftl::StaticVector vector = ftl::init::list<std::string>("abc")()(3u, '?');
171 //
172 // static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 3>>);
173 // assert(vector.full());
174 // assert(vector[0] == "abc");
175 // assert(vector[1].empty());
176 // assert(vector[2] == "???");
177 //
178 template <typename U, std::size_t Size, std::size_t... Sizes, typename... Types>
179 StaticVector(InitializerList<U, std::index_sequence<Size, Sizes...>, Types...>&& list)
180 : StaticVector(std::index_sequence<0, 0, Size>{}, std::make_index_sequence<Size>{},
Dominik Laskowski17f6b972022-01-25 13:41:52 -0800181 std::index_sequence<Sizes...>{}, list.tuple) {
182 static_assert(sizeof...(Sizes) < N, "Too many elements");
183 }
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800184
185 ~StaticVector() { std::destroy(begin(), end()); }
186
187 StaticVector& operator=(const StaticVector& other) {
188 StaticVector copy(other);
189 swap(copy);
190 return *this;
191 }
192
193 StaticVector& operator=(StaticVector&& other) {
Dominik Laskowski44828ce2021-09-13 11:00:22 -0700194 clear();
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800195 swap<true>(other);
196 return *this;
197 }
198
199 // IsEmpty enables a fast path when the vector is known to be empty at compile time.
200 template <bool IsEmpty = false>
201 void swap(StaticVector&);
202
203 static constexpr size_type max_size() { return N; }
204 size_type size() const { return size_; }
205
206 bool empty() const { return size() == 0; }
207 bool full() const { return size() == max_size(); }
208
209 iterator begin() { return std::launder(reinterpret_cast<pointer>(data_)); }
210 iterator end() { return begin() + size(); }
211
212 using Iter::begin;
213 using Iter::end;
214
215 using Iter::cbegin;
216 using Iter::cend;
217
218 using Iter::rbegin;
219 using Iter::rend;
220
221 using Iter::crbegin;
222 using Iter::crend;
223
224 using Iter::last;
225
226 using Iter::back;
227 using Iter::front;
228
229 using Iter::operator[];
230
231 // 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 //
241 template <typename... Args>
242 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));
247 }
248
249 // Appends an element, and returns an iterator to it. If the vector is full, the element is not
250 // inserted, and the end() iterator is returned.
251 //
252 // On success, the end() iterator is invalidated.
253 //
254 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)...);
258 ++size_;
259 return it;
260 }
261
262 // 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 //
266 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) {
273 // Two statements for sequence point.
274 const iterator it = emplace_back(std::move(v));
275 return it != end();
276 }
277
278 // 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 //
282 void pop_back() { unstable_erase(last()); }
283
Dominik Laskowski44828ce2021-09-13 11:00:22 -0700284 // Removes all elements.
285 //
286 // All iterators are invalidated.
287 //
288 void clear() {
289 std::destroy(begin(), end());
290 size_ = 0;
291 }
292
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800293 // Erases an element, but does not preserve order. Rather than shifting subsequent elements,
294 // this moves the last element to the slot of the erased element.
295 //
296 // The last() and end() iterators, as well as those to the erased element, are invalidated.
297 //
298 void unstable_erase(const_iterator it) {
299 std::destroy_at(it);
300 if (it != last()) {
301 // Move last element and destroy its source for destructor side effects. This is only
302 // safe because exceptions are disabled.
303 construct_at(it, std::move(back()));
304 std::destroy_at(last());
Dominik Laskowski03572372020-10-27 22:36:00 -0700305 }
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800306 --size_;
307 }
Dominik Laskowski03572372020-10-27 22:36:00 -0700308
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800309 private:
310 // Recursion for variadic constructor.
311 template <std::size_t I, typename E, typename... Es>
312 StaticVector(std::index_sequence<I>, E&& element, Es&&... elements)
313 : StaticVector(std::index_sequence<I + 1>{}, std::forward<Es>(elements)...) {
314 construct_at(begin() + I, std::forward<E>(element));
315 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700316
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800317 // Base case for variadic constructor.
318 template <std::size_t I>
319 explicit StaticVector(std::index_sequence<I>) : size_(I) {}
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700320
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800321 // Recursion for in-place constructor.
322 //
323 // Construct element I by extracting its arguments from the InitializerList tuple. ArgIndex
324 // is the position of its first argument in Args, and ArgCount is the number of arguments.
325 // The Indices sequence corresponds to [0, ArgCount).
326 //
327 // The Sizes sequence lists the argument counts for elements after I, so Size is the ArgCount
328 // for the next element. The recursion stops when Sizes is empty for the last element.
329 //
330 template <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
331 std::size_t Size, std::size_t... Sizes, typename... Args>
332 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
333 std::index_sequence<Size, Sizes...>, std::tuple<Args...>& tuple)
334 : StaticVector(std::index_sequence<I + 1, ArgIndex + ArgCount, Size>{},
335 std::make_index_sequence<Size>{}, std::index_sequence<Sizes...>{}, tuple) {
336 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
337 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700338
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800339 // Base case for in-place constructor.
340 template <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
341 typename... Args>
342 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
343 std::index_sequence<>, std::tuple<Args...>& tuple)
344 : size_(I + 1) {
345 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
346 }
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700347
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800348 size_type size_ = 0;
349 std::aligned_storage_t<sizeof(value_type), alignof(value_type)> data_[N];
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700350};
351
352// Deduction guide for array constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800353template <typename T, std::size_t N>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700354StaticVector(T (&)[N]) -> StaticVector<std::remove_cv_t<T>, N>;
355
356// Deduction guide for variadic constructor.
357template <typename T, typename... Us, typename V = std::decay_t<T>,
358 typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>>
359StaticVector(T&&, Us&&...) -> StaticVector<V, 1 + sizeof...(Us)>;
360
361// Deduction guide for in-place constructor.
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800362template <typename T, std::size_t... Sizes, typename... Types>
Dominik Laskowskiccd50a42020-10-30 19:56:38 -0700363StaticVector(InitializerList<T, std::index_sequence<Sizes...>, Types...>&&)
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800364 -> StaticVector<T, sizeof...(Sizes)>;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700365
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800366template <typename T, std::size_t N>
367template <bool IsEmpty>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700368void StaticVector<T, N>::swap(StaticVector& other) {
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800369 auto [to, from] = std::make_pair(this, &other);
370 if (from == this) return;
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700371
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800372 // Assume this vector has fewer elements, so the excess of the other vector will be moved to it.
373 auto [min, max] = std::make_pair(size(), other.size());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700374
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800375 // No elements to swap if moving into an empty vector.
376 if constexpr (IsEmpty) {
377 assert(min == 0);
378 } else {
379 if (min > max) {
380 std::swap(from, to);
381 std::swap(min, max);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700382 }
383
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800384 // Swap elements [0, min).
385 std::swap_ranges(begin(), begin() + min, other.begin());
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700386
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800387 // No elements to move if sizes are equal.
388 if (min == max) return;
389 }
390
391 // Move elements [min, max) and destroy their source for destructor side effects.
392 const auto [first, last] = std::make_pair(from->begin() + min, from->begin() + max);
393 std::uninitialized_move(first, last, to->begin() + min);
394 std::destroy(first, last);
395
396 std::swap(size_, other.size_);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700397}
398
Dominik Laskowski5444fc82020-11-24 13:41:10 -0800399template <typename T, std::size_t N>
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700400inline void swap(StaticVector<T, N>& lhs, StaticVector<T, N>& rhs) {
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800401 lhs.swap(rhs);
Dominik Laskowski6fdf1142020-10-07 12:09:09 -0700402}
403
Dominik Laskowskie21dbed2020-12-04 20:51:43 -0800404} // namespace android::ftl