• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/details/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 // 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 //
45 // StaticVector<T, 1> is analogous to an iterable std::optional.
46 // StaticVector<T, 0> is an error.
47 //
48 // Example usage:
49 //
50 //   ftl::StaticVector<char, 3> vector;
51 //   assert(vector.empty());
52 //
53 //   vector = {'a', 'b'};
54 //   assert(vector.size() == 2u);
55 //
56 //   vector.push_back('c');
57 //   assert(vector.full());
58 //
59 //   assert(!vector.push_back('d'));
60 //   assert(vector.size() == 3u);
61 //
62 //   vector.unstable_erase(vector.begin());
63 //   assert(vector == (ftl::StaticVector{'c', 'b'}));
64 //
65 //   vector.pop_back();
66 //   assert(vector.back() == 'c');
67 //
68 //   const char array[] = "hi";
69 //   vector = ftl::StaticVector(array);
70 //   assert(vector == (ftl::StaticVector{'h', 'i', '\0'}));
71 //
72 //   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] == "???");
77 //
78 template <typename T, std::size_t N>
79 class StaticVector final : details::ArrayTraits<T>,
80                            details::ArrayIterators<StaticVector<T, N>, T>,
81                            details::ArrayComparators<StaticVector> {
82   static_assert(N > 0);
83 
84   // For constructor that moves from a smaller convertible vector.
85   template <typename, std::size_t>
86   friend class StaticVector;
87 
88   using details::ArrayTraits<T>::construct_at;
89   using details::ArrayTraits<T>::replace_at;
90   using details::ArrayTraits<T>::in_place_swap_ranges;
91   using details::ArrayTraits<T>::uninitialized_copy;
92 
93   using Iter = details::ArrayIterators<StaticVector, T>;
94   friend Iter;
95 
96   // 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>>>;
104 
105  public:
106   FTL_ARRAY_TRAIT(T, value_type);
107   FTL_ARRAY_TRAIT(T, size_type);
108   FTL_ARRAY_TRAIT(T, difference_type);
109 
110   FTL_ARRAY_TRAIT(T, pointer);
111   FTL_ARRAY_TRAIT(T, reference);
112   FTL_ARRAY_TRAIT(T, iterator);
113   FTL_ARRAY_TRAIT(T, reverse_iterator);
114 
115   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);
119 
120   // Creates an empty vector.
121   StaticVector() = default;
122 
123   // Copies and moves a vector, respectively.
StaticVector(const StaticVector & other)124   StaticVector(const StaticVector& other)
125       : StaticVector(kIteratorRange, other.begin(), other.end()) {}
126 
StaticVector(StaticVector && other)127   StaticVector(StaticVector&& other) { swap<true>(other); }
128 
129   // Copies at most N elements from a smaller convertible vector.
130   template <typename U, std::size_t M>
StaticVector(const StaticVector<U,M> & other)131   StaticVector(const StaticVector<U, M>& other)
132       : StaticVector(kIteratorRange, other.begin(), other.end()) {
133     static_assert(N >= M, "Insufficient capacity");
134   }
135 
136   // Copies at most N elements from a smaller convertible array.
137   template <typename U, std::size_t M>
StaticVector(U (& array)[M])138   explicit StaticVector(U (&array)[M])
139       : StaticVector(kIteratorRange, std::begin(array), std::end(array)) {
140     static_assert(N >= M, "Insufficient capacity");
141   }
142 
143   // 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>{}>>
StaticVector(Iterator first,Iterator last)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>
StaticVector(IteratorRangeTag,Iterator first,Iterator last)154   StaticVector(IteratorRangeTag, Iterator first, Iterator last)
155       : size_(std::min(max_size(), static_cast<size_type>(std::distance(first, last)))) {
156     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>
StaticVector(StaticVector<U,M> && other)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_);
168   }
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>>>
StaticVector(E && element,Es &&...elements)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>
StaticVector(InitializerList<U,std::index_sequence<Size,Sizes...>,Types...> && list)204   StaticVector(InitializerList<U, std::index_sequence<Size, Sizes...>, Types...>&& list)
205       : StaticVector(std::index_sequence<0, 0, Size>{}, std::make_index_sequence<Size>{},
206                      std::index_sequence<Sizes...>{}, list.tuple) {
207     static_assert(sizeof...(Sizes) < N, "Too many elements");
208   }
209 
~StaticVector()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) {
219     clear();
220     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 
max_size()228   static constexpr size_type max_size() { return N; }
size()229   size_type size() const { return size_; }
230 
empty()231   bool empty() const { return size() == 0; }
full()232   bool full() const { return size() == max_size(); }
233 
begin()234   iterator begin() { return std::launder(reinterpret_cast<pointer>(data_)); }
end()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>
replace(const_iterator it,Args &&...args)267   reference replace(const_iterator it, Args&&... args) {
268     return replace_at(it, std::forward<Args>(args)...);
269   }
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>
emplace_back(Args &&...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   //
push_back(const value_type & v)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 
push_back(value_type && v)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   //
pop_back()304   void pop_back() { unstable_erase(last()); }
305 
306   // Removes all elements.
307   //
308   // All iterators are invalidated.
309   //
clear()310   void clear() {
311     std::destroy(begin(), end());
312     size_ = 0;
313   }
314 
315   // 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   //
unstable_erase(const_iterator it)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());
327     }
328     --size_;
329   }
330 
331  private:
332   // Recursion for variadic constructor.
333   template <std::size_t I, typename E, typename... Es>
StaticVector(std::index_sequence<I>,E && element,Es &&...elements)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   }
338 
339   // Base case for variadic constructor.
340   template <std::size_t I>
StaticVector(std::index_sequence<I>)341   explicit StaticVector(std::index_sequence<I>) : size_(I) {}
342 
343   // 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>
StaticVector(std::index_sequence<I,ArgIndex,ArgCount>,std::index_sequence<Indices...>,std::index_sequence<Size,Sizes...>,std::tuple<Args...> & tuple)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   }
360 
361   // 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>
StaticVector(std::index_sequence<I,ArgIndex,ArgCount>,std::index_sequence<Indices...>,std::index_sequence<>,std::tuple<Args...> & tuple)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   }
369 
370   size_type size_ = 0;
371   std::aligned_storage_t<sizeof(value_type), alignof(value_type)> data_[N];
372 };
373 
374 // Deduction guide for array constructor.
375 template <typename T, std::size_t N>
376 StaticVector(T (&)[N]) -> StaticVector<std::remove_cv_t<T>, N>;
377 
378 // Deduction guide for variadic constructor.
379 template <typename T, typename... Us, typename V = std::decay_t<T>,
380           typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>>
381 StaticVector(T&&, Us&&...) -> StaticVector<V, 1 + sizeof...(Us)>;
382 
383 // Deduction guide for in-place constructor.
384 template <typename T, std::size_t... Sizes, typename... Types>
385 StaticVector(InitializerList<T, std::index_sequence<Sizes...>, Types...>&&)
386     -> StaticVector<T, sizeof...(Sizes)>;
387 
388 template <typename T, std::size_t N>
389 template <bool IsEmpty>
swap(StaticVector & other)390 void StaticVector<T, N>::swap(StaticVector& other) {
391   auto [to, from] = std::make_pair(this, &other);
392   if (from == this) return;
393 
394   // 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());
396 
397   // 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);
404     }
405 
406     // Swap elements [0, min).
407     in_place_swap_ranges(begin(), begin() + min, other.begin());
408 
409     // 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_);
419 }
420 
421 template <typename T, std::size_t N>
swap(StaticVector<T,N> & lhs,StaticVector<T,N> & rhs)422 inline void swap(StaticVector<T, N>& lhs, StaticVector<T, N>& rhs) {
423   lhs.swap(rhs);
424 }
425 
426 }  // namespace android::ftl
427