1 /*
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
19 #include <ftl/array_traits.h>
20 #include <ftl/initializer_list.h>
21
22 #include <algorithm>
23 #include <cassert>
24 #include <iterator>
25 #include <memory>
26 #include <type_traits>
27 #include <utility>
28
29 namespace android::ftl {
30
31 constexpr struct IteratorRangeTag {
32 } kIteratorRange;
33
34 // Fixed-capacity, statically allocated counterpart of std::vector. Like std::array, StaticVector
35 // 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
37 // default constructor, since elements are constructed in place as the vector grows. Operations that
38 // 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,
40 // and the replace operation that destructively emplaces.
41 //
42 // StaticVector<T, 1> is analogous to an iterable std::optional.
43 // StaticVector<T, 0> is an error.
44 //
45 // Example usage:
46 //
47 // ftl::StaticVector<char, 3> vector;
48 // assert(vector.empty());
49 //
50 // vector = {'a', 'b'};
51 // assert(vector.size() == 2u);
52 //
53 // vector.push_back('c');
54 // assert(vector.full());
55 //
56 // assert(!vector.push_back('d'));
57 // assert(vector.size() == 3u);
58 //
59 // vector.unstable_erase(vector.begin());
60 // assert(vector == (ftl::StaticVector{'c', 'b'}));
61 //
62 // vector.pop_back();
63 // assert(vector.back() == 'c');
64 //
65 // const char array[] = "hi";
66 // vector = ftl::StaticVector(array);
67 // assert(vector == (ftl::StaticVector{'h', 'i', '\0'}));
68 //
69 // 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] == "???");
74 //
75 template <typename T, std::size_t N>
76 class StaticVector final : ArrayTraits<T>,
77 ArrayIterators<StaticVector<T, N>, T>,
78 ArrayComparators<StaticVector> {
79 static_assert(N > 0);
80
81 using ArrayTraits<T>::construct_at;
82
83 using Iter = ArrayIterators<StaticVector, T>;
84 friend Iter;
85
86 // 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>>>;
94
95 public:
96 FTL_ARRAY_TRAIT(T, value_type);
97 FTL_ARRAY_TRAIT(T, size_type);
98 FTL_ARRAY_TRAIT(T, difference_type);
99
100 FTL_ARRAY_TRAIT(T, pointer);
101 FTL_ARRAY_TRAIT(T, reference);
102 FTL_ARRAY_TRAIT(T, iterator);
103 FTL_ARRAY_TRAIT(T, reverse_iterator);
104
105 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);
109
110 // Creates an empty vector.
111 StaticVector() = default;
112
113 // Copies and moves a vector, respectively.
StaticVector(const StaticVector & other)114 StaticVector(const StaticVector& other)
115 : StaticVector(kIteratorRange, other.begin(), other.end()) {}
116
StaticVector(StaticVector && other)117 StaticVector(StaticVector&& other) { swap<true>(other); }
118
119 // 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>>
StaticVector(const StaticVector<U,M> & other)121 StaticVector(const StaticVector<U, M>& other)
122 : StaticVector(kIteratorRange, other.begin(), other.end()) {}
123
124 // Copies at most N elements from an array.
125 template <typename U, std::size_t M>
StaticVector(U (& array)[M])126 explicit StaticVector(U (&array)[M])
127 : StaticVector(kIteratorRange, std::begin(array), std::end(array)) {}
128
129 // 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>{}>>
StaticVector(Iterator first,Iterator last)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>
StaticVector(IteratorRangeTag,Iterator first,Iterator last)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>>>
StaticVector(E && element,Es &&...elements)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>
StaticVector(InitializerList<U,std::index_sequence<Size,Sizes...>,Types...> && list)179 StaticVector(InitializerList<U, std::index_sequence<Size, Sizes...>, Types...>&& list)
180 : StaticVector(std::index_sequence<0, 0, Size>{}, std::make_index_sequence<Size>{},
181 std::index_sequence<Sizes...>{}, list.tuple) {}
182
~StaticVector()183 ~StaticVector() { std::destroy(begin(), end()); }
184
185 StaticVector& operator=(const StaticVector& other) {
186 StaticVector copy(other);
187 swap(copy);
188 return *this;
189 }
190
191 StaticVector& operator=(StaticVector&& other) {
192 std::destroy(begin(), end());
193 size_ = 0;
194 swap<true>(other);
195 return *this;
196 }
197
198 // IsEmpty enables a fast path when the vector is known to be empty at compile time.
199 template <bool IsEmpty = false>
200 void swap(StaticVector&);
201
max_size()202 static constexpr size_type max_size() { return N; }
size()203 size_type size() const { return size_; }
204
empty()205 bool empty() const { return size() == 0; }
full()206 bool full() const { return size() == max_size(); }
207
begin()208 iterator begin() { return std::launder(reinterpret_cast<pointer>(data_)); }
end()209 iterator end() { return begin() + size(); }
210
211 using Iter::begin;
212 using Iter::end;
213
214 using Iter::cbegin;
215 using Iter::cend;
216
217 using Iter::rbegin;
218 using Iter::rend;
219
220 using Iter::crbegin;
221 using Iter::crend;
222
223 using Iter::last;
224
225 using Iter::back;
226 using Iter::front;
227
228 using Iter::operator[];
229
230 // Replaces an element, and returns a reference to it. The iterator must be dereferenceable, so
231 // replacing at end() is erroneous.
232 //
233 // The element is emplaced via move constructor, so type T does not need to define copy/move
234 // assignment, e.g. its data members may be const.
235 //
236 // The arguments may directly or indirectly refer to the element being replaced.
237 //
238 // Iterators to the replaced element point to its replacement, and others remain valid.
239 //
240 template <typename... Args>
replace(const_iterator it,Args &&...args)241 reference replace(const_iterator it, Args&&... args) {
242 value_type element{std::forward<Args>(args)...};
243 std::destroy_at(it);
244 // This is only safe because exceptions are disabled.
245 return *construct_at(it, std::move(element));
246 }
247
248 // Appends an element, and returns an iterator to it. If the vector is full, the element is not
249 // inserted, and the end() iterator is returned.
250 //
251 // On success, the end() iterator is invalidated.
252 //
253 template <typename... Args>
emplace_back(Args &&...args)254 iterator emplace_back(Args&&... args) {
255 if (full()) return end();
256 const iterator it = construct_at(end(), std::forward<Args>(args)...);
257 ++size_;
258 return it;
259 }
260
261 // Appends an element unless the vector is full, and returns whether the element was inserted.
262 //
263 // On success, the end() iterator is invalidated.
264 //
push_back(const value_type & v)265 bool push_back(const value_type& v) {
266 // Two statements for sequence point.
267 const iterator it = emplace_back(v);
268 return it != end();
269 }
270
push_back(value_type && v)271 bool push_back(value_type&& v) {
272 // Two statements for sequence point.
273 const iterator it = emplace_back(std::move(v));
274 return it != end();
275 }
276
277 // Removes the last element. The vector must not be empty, or the call is erroneous.
278 //
279 // The last() and end() iterators are invalidated.
280 //
pop_back()281 void pop_back() { unstable_erase(last()); }
282
283 // Erases an element, but does not preserve order. Rather than shifting subsequent elements,
284 // this moves the last element to the slot of the erased element.
285 //
286 // The last() and end() iterators, as well as those to the erased element, are invalidated.
287 //
unstable_erase(const_iterator it)288 void unstable_erase(const_iterator it) {
289 std::destroy_at(it);
290 if (it != last()) {
291 // Move last element and destroy its source for destructor side effects. This is only
292 // safe because exceptions are disabled.
293 construct_at(it, std::move(back()));
294 std::destroy_at(last());
295 }
296 --size_;
297 }
298
299 private:
300 // Recursion for variadic constructor.
301 template <std::size_t I, typename E, typename... Es>
StaticVector(std::index_sequence<I>,E && element,Es &&...elements)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 <std::size_t I>
StaticVector(std::index_sequence<I>)309 explicit StaticVector(std::index_sequence<I>) : size_(I) {}
310
311 // 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 <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
321 std::size_t Size, std::size_t... Sizes, typename... Args>
StaticVector(std::index_sequence<I,ArgIndex,ArgCount>,std::index_sequence<Indices...>,std::index_sequence<Size,Sizes...>,std::tuple<Args...> & tuple)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 <std::size_t I, std::size_t ArgIndex, std::size_t ArgCount, std::size_t... Indices,
331 typename... Args>
StaticVector(std::index_sequence<I,ArgIndex,ArgCount>,std::index_sequence<Indices...>,std::index_sequence<>,std::tuple<Args...> & tuple)332 StaticVector(std::index_sequence<I, ArgIndex, ArgCount>, std::index_sequence<Indices...>,
333 std::index_sequence<>, std::tuple<Args...>& tuple)
334 : size_(I + 1) {
335 construct_at(begin() + I, std::move(std::get<ArgIndex + Indices>(tuple))...);
336 }
337
338 size_type size_ = 0;
339 std::aligned_storage_t<sizeof(value_type), alignof(value_type)> data_[N];
340 };
341
342 // Deduction guide for array constructor.
343 template <typename T, std::size_t N>
344 StaticVector(T (&)[N]) -> StaticVector<std::remove_cv_t<T>, N>;
345
346 // Deduction guide for variadic constructor.
347 template <typename T, typename... Us, typename V = std::decay_t<T>,
348 typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>>
349 StaticVector(T&&, Us&&...) -> StaticVector<V, 1 + sizeof...(Us)>;
350
351 // Deduction guide for in-place constructor.
352 template <typename T, std::size_t... Sizes, typename... Types>
353 StaticVector(InitializerList<T, std::index_sequence<Sizes...>, Types...>&&)
354 -> StaticVector<T, sizeof...(Sizes)>;
355
356 template <typename T, std::size_t N>
357 template <bool IsEmpty>
swap(StaticVector & other)358 void StaticVector<T, N>::swap(StaticVector& other) {
359 auto [to, from] = std::make_pair(this, &other);
360 if (from == this) return;
361
362 // Assume this vector has fewer elements, so the excess of the other vector will be moved to it.
363 auto [min, max] = std::make_pair(size(), other.size());
364
365 // No elements to swap if moving into an empty vector.
366 if constexpr (IsEmpty) {
367 assert(min == 0);
368 } else {
369 if (min > max) {
370 std::swap(from, to);
371 std::swap(min, max);
372 }
373
374 // Swap elements [0, min).
375 std::swap_ranges(begin(), begin() + min, other.begin());
376
377 // No elements to move if sizes are equal.
378 if (min == max) return;
379 }
380
381 // Move elements [min, max) and destroy their source for destructor side effects.
382 const auto [first, last] = std::make_pair(from->begin() + min, from->begin() + max);
383 std::uninitialized_move(first, last, to->begin() + min);
384 std::destroy(first, last);
385
386 std::swap(size_, other.size_);
387 }
388
389 template <typename T, std::size_t N>
swap(StaticVector<T,N> & lhs,StaticVector<T,N> & rhs)390 inline void swap(StaticVector<T, N>& lhs, StaticVector<T, N>& rhs) {
391 lhs.swap(rhs);
392 }
393
394 } // namespace android::ftl
395