| Dominik Laskowski | 6fdf114 | 2020-10-07 12:09:09 -0700 | [diff] [blame] | 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 <algorithm> | 
|  | 20 | #include <cassert> | 
|  | 21 | #include <iterator> | 
|  | 22 | #include <memory> | 
|  | 23 | #include <new> | 
|  | 24 | #include <type_traits> | 
|  | 25 | #include <utility> | 
|  | 26 |  | 
|  | 27 | namespace android::ftl { | 
|  | 28 |  | 
|  | 29 | // Fixed-capacity, statically allocated counterpart of std::vector. Akin to std::array, StaticVector | 
|  | 30 | // allocates contiguous storage for N elements of type T at compile time, but stores at most (rather | 
|  | 31 | // than exactly) N elements. Unlike std::array, its default constructor does not require T to have a | 
|  | 32 | // default constructor, since elements are constructed in-place as the vector grows. Operations that | 
|  | 33 | // insert an element, such as push_back and emplace, fail when the vector is full. The API otherwise | 
|  | 34 | // adheres to standard containers, except the unstable_erase operation that does not shift elements, | 
|  | 35 | // and the replace operation that destructively emplaces. | 
|  | 36 | // | 
|  | 37 | // StaticVector<T, 1> is analogous to an iterable std::optional, but StaticVector<T, 0> is an error. | 
|  | 38 | // | 
|  | 39 | // Example usage: | 
|  | 40 | // | 
|  | 41 | //     ftl::StaticVector<char, 3> vector; | 
|  | 42 | //     assert(vector.empty()); | 
|  | 43 | // | 
|  | 44 | //     vector = {'a', 'b'}; | 
|  | 45 | //     assert(vector.size() == 2u); | 
|  | 46 | // | 
|  | 47 | //     vector.push_back('c'); | 
|  | 48 | //     assert(vector.full()); | 
|  | 49 | // | 
|  | 50 | //     assert(!vector.push_back('d')); | 
|  | 51 | //     assert(vector.size() == 3u); | 
|  | 52 | // | 
|  | 53 | //     vector.unstable_erase(vector.begin()); | 
|  | 54 | //     assert(vector == (ftl::StaticVector{'c', 'b'})); | 
|  | 55 | // | 
|  | 56 | //     vector.pop_back(); | 
|  | 57 | //     assert(vector.back() == 'c'); | 
|  | 58 | // | 
|  | 59 | //     const char array[] = "hi"; | 
|  | 60 | //     vector = ftl::StaticVector(array); | 
|  | 61 | //     assert(vector == (ftl::StaticVector{'h', 'i', '\0'})); | 
|  | 62 | // | 
|  | 63 | template <typename T, size_t N> | 
|  | 64 | class StaticVector { | 
|  | 65 | static_assert(N > 0); | 
|  | 66 |  | 
|  | 67 | template <typename I> | 
|  | 68 | using IsInputIterator = std::is_base_of<std::input_iterator_tag, | 
|  | 69 | typename std::iterator_traits<I>::iterator_category>; | 
|  | 70 |  | 
|  | 71 | public: | 
|  | 72 | using value_type = T; | 
|  | 73 | using size_type = size_t; | 
|  | 74 | using difference_type = ptrdiff_t; | 
|  | 75 |  | 
|  | 76 | using pointer = value_type*; | 
|  | 77 | using reference = value_type&; | 
|  | 78 | using iterator = pointer; | 
|  | 79 | using reverse_iterator = std::reverse_iterator<iterator>; | 
|  | 80 |  | 
|  | 81 | using const_pointer = const value_type*; | 
|  | 82 | using const_reference = const value_type&; | 
|  | 83 | using const_iterator = const_pointer; | 
|  | 84 | using const_reverse_iterator = std::reverse_iterator<const_iterator>; | 
|  | 85 |  | 
|  | 86 | // Creates an empty vector. | 
|  | 87 | StaticVector() = default; | 
|  | 88 |  | 
|  | 89 | // Copies and moves a vector, respectively. | 
|  | 90 | StaticVector(const StaticVector& other) : StaticVector(other.begin(), other.end()) {} | 
|  | 91 | StaticVector(StaticVector&& other) { swap<Empty>(other); } | 
|  | 92 |  | 
|  | 93 | // Copies at most N elements from a smaller convertible vector. | 
|  | 94 | template <typename U, size_t M, typename = std::enable_if_t<M <= N>> | 
|  | 95 | StaticVector(const StaticVector<U, M>& other) : StaticVector(other.begin(), other.end()) {} | 
|  | 96 |  | 
|  | 97 | // Copies at most N elements from an array. | 
|  | 98 | template <typename U, size_t M> | 
|  | 99 | explicit StaticVector(U (&array)[M]) : StaticVector(std::begin(array), std::end(array)) {} | 
|  | 100 |  | 
|  | 101 | // Copies at most N elements from the range [first, last). | 
|  | 102 | template <typename Iterator, typename = std::enable_if_t<IsInputIterator<Iterator>{}>> | 
|  | 103 | StaticVector(Iterator first, Iterator last) | 
|  | 104 | : mSize(std::min(max_size(), static_cast<size_type>(std::distance(first, last)))) { | 
|  | 105 | std::uninitialized_copy(first, first + mSize, begin()); | 
|  | 106 | } | 
|  | 107 |  | 
|  | 108 | // Constructs at most N elements. The template arguments T and N are inferred using the | 
|  | 109 | // deduction guide defined below. Note that T is determined from the first element, and | 
|  | 110 | // subsequent elements must have convertible types: | 
|  | 111 | // | 
|  | 112 | //     ftl::StaticVector vector = {1, 2, 3}; | 
|  | 113 | //     static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<int, 3>>); | 
|  | 114 | // | 
|  | 115 | //     const auto copy = "quince"s; | 
|  | 116 | //     auto move = "tart"s; | 
|  | 117 | //     ftl::StaticVector vector = {copy, std::move(move)}; | 
|  | 118 | // | 
|  | 119 | //     static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 2>>); | 
|  | 120 | // | 
|  | 121 | template <typename E, typename... Es, | 
|  | 122 | typename = std::enable_if_t<std::is_constructible_v<value_type, E>>> | 
|  | 123 | StaticVector(E&& element, Es&&... elements) | 
|  | 124 | : StaticVector(std::index_sequence<0>{}, std::forward<E>(element), | 
|  | 125 | std::forward<Es>(elements)...) { | 
|  | 126 | static_assert(sizeof...(elements) < N, "Too many elements"); | 
|  | 127 | } | 
|  | 128 |  | 
|  | 129 | // Constructs at most N elements. The template arguments T and N are inferred using the | 
|  | 130 | // deduction guide defined below. Element types must be convertible to the specified T: | 
|  | 131 | // | 
|  | 132 | //     ftl::StaticVector vector(std::in_place_type<std::string>, "red", "velvet", "cake"); | 
|  | 133 | //     static_assert(std::is_same_v<decltype(vector), ftl::StaticVector<std::string, 3>>); | 
|  | 134 | // | 
|  | 135 | template <typename... Es> | 
|  | 136 | explicit StaticVector(std::in_place_type_t<T>, Es... elements) | 
|  | 137 | : StaticVector(std::forward<Es>(elements)...) {} | 
|  | 138 |  | 
|  | 139 | ~StaticVector() { std::destroy(begin(), end()); } | 
|  | 140 |  | 
|  | 141 | StaticVector& operator=(const StaticVector& other) { | 
|  | 142 | StaticVector copy(other); | 
|  | 143 | swap(copy); | 
|  | 144 | return *this; | 
|  | 145 | } | 
|  | 146 |  | 
|  | 147 | StaticVector& operator=(StaticVector&& other) { | 
|  | 148 | std::destroy(begin(), end()); | 
|  | 149 | mSize = 0; | 
|  | 150 | swap<Empty>(other); | 
|  | 151 | return *this; | 
|  | 152 | } | 
|  | 153 |  | 
|  | 154 | template <typename = void> | 
|  | 155 | void swap(StaticVector&); | 
|  | 156 |  | 
|  | 157 | size_type max_size() const { return N; } | 
|  | 158 | size_type size() const { return mSize; } | 
|  | 159 |  | 
|  | 160 | bool empty() const { return size() == 0; } | 
|  | 161 | bool full() const { return size() == max_size(); } | 
|  | 162 |  | 
|  | 163 | iterator begin() { return std::launder(reinterpret_cast<pointer>(mData)); } | 
|  | 164 | const_iterator begin() const { return cbegin(); } | 
|  | 165 | const_iterator cbegin() const { return mut().begin(); } | 
|  | 166 |  | 
|  | 167 | iterator end() { return begin() + size(); } | 
|  | 168 | const_iterator end() const { return cend(); } | 
|  | 169 | const_iterator cend() const { return mut().end(); } | 
|  | 170 |  | 
|  | 171 | reverse_iterator rbegin() { return std::make_reverse_iterator(end()); } | 
|  | 172 | const_reverse_iterator rbegin() const { return crbegin(); } | 
|  | 173 | const_reverse_iterator crbegin() const { return mut().rbegin(); } | 
|  | 174 |  | 
|  | 175 | reverse_iterator rend() { return std::make_reverse_iterator(begin()); } | 
|  | 176 | const_reverse_iterator rend() const { return crend(); } | 
|  | 177 | const_reverse_iterator crend() const { return mut().rend(); } | 
|  | 178 |  | 
|  | 179 | iterator last() { return end() - 1; } | 
|  | 180 | const_iterator last() const { return mut().last(); } | 
|  | 181 |  | 
|  | 182 | reference front() { return *begin(); } | 
|  | 183 | const_reference front() const { return mut().front(); } | 
|  | 184 |  | 
|  | 185 | reference back() { return *last(); } | 
|  | 186 | const_reference back() const { return mut().back(); } | 
|  | 187 |  | 
|  | 188 | reference operator[](size_type i) { return *(begin() + i); } | 
|  | 189 | const_reference operator[](size_type i) const { return mut()[i]; } | 
|  | 190 |  | 
|  | 191 | // Replaces an element, and returns an iterator to it. If the vector is full, the element is not | 
|  | 192 | // replaced, and the end iterator is returned. | 
|  | 193 | template <typename... Args> | 
|  | 194 | iterator replace(const_iterator cit, Args&&... args) { | 
|  | 195 | if (full()) return end(); | 
|  | 196 | // Append element, and move into place if not last. | 
|  | 197 | emplace_back(std::forward<Args>(args)...); | 
|  | 198 | if (cit != last()) unstable_erase(cit); | 
|  | 199 | return const_cast<iterator>(cit); | 
|  | 200 | } | 
|  | 201 |  | 
|  | 202 | // Appends an element, and returns an iterator to it. If the vector is full, the element is not | 
|  | 203 | // inserted, and the end iterator is returned. | 
|  | 204 | template <typename... Args> | 
|  | 205 | iterator emplace_back(Args&&... args) { | 
|  | 206 | if (full()) return end(); | 
|  | 207 | const iterator it = construct_at(end(), std::forward<Args>(args)...); | 
|  | 208 | ++mSize; | 
|  | 209 | return it; | 
|  | 210 | } | 
|  | 211 |  | 
|  | 212 | // Erases an element, but does not preserve order. Rather than shifting subsequent elements, | 
|  | 213 | // this moves the last element to the slot of the erased element. | 
|  | 214 | void unstable_erase(const_iterator it) { | 
|  | 215 | std::destroy_at(it); | 
|  | 216 | if (it != last()) { | 
|  | 217 | // Move last element and destroy its source for destructor side effects. | 
|  | 218 | construct_at(it, std::move(back())); | 
|  | 219 | std::destroy_at(last()); | 
|  | 220 | } | 
|  | 221 | --mSize; | 
|  | 222 | } | 
|  | 223 |  | 
|  | 224 | bool push_back(value_type v) { | 
|  | 225 | // Two statements for sequence point. | 
|  | 226 | const iterator it = emplace_back(std::move(v)); | 
|  | 227 | return it != end(); | 
|  | 228 | } | 
|  | 229 |  | 
|  | 230 | void pop_back() { unstable_erase(last()); } | 
|  | 231 |  | 
|  | 232 | private: | 
|  | 233 | struct Empty {}; | 
|  | 234 |  | 
|  | 235 | StaticVector& mut() const { return *const_cast<StaticVector*>(this); } | 
|  | 236 |  | 
|  | 237 | // Recursion for variadic constructor. | 
|  | 238 | template <size_t I, typename E, typename... Es> | 
|  | 239 | StaticVector(std::index_sequence<I>, E&& element, Es&&... elements) | 
|  | 240 | : StaticVector(std::index_sequence<I + 1>{}, std::forward<Es>(elements)...) { | 
|  | 241 | construct_at(begin() + I, std::forward<E>(element)); | 
|  | 242 | } | 
|  | 243 |  | 
|  | 244 | // Base case for variadic constructor. | 
|  | 245 | template <size_t I> | 
|  | 246 | explicit StaticVector(std::index_sequence<I>) : mSize(I) {} | 
|  | 247 |  | 
|  | 248 | // TODO: Replace with std::construct_at in C++20. | 
|  | 249 | template <typename... Args> | 
|  | 250 | static pointer construct_at(const_iterator it, Args&&... args) { | 
|  | 251 | void* const ptr = const_cast<void*>(static_cast<const void*>(it)); | 
|  | 252 | return new (ptr) value_type{std::forward<Args>(args)...}; | 
|  | 253 | } | 
|  | 254 |  | 
|  | 255 | size_type mSize = 0; | 
|  | 256 | std::aligned_storage_t<sizeof(value_type), alignof(value_type)> mData[N]; | 
|  | 257 | }; | 
|  | 258 |  | 
|  | 259 | // Deduction guide for array constructor. | 
|  | 260 | template <typename T, size_t N> | 
|  | 261 | StaticVector(T (&)[N]) -> StaticVector<std::remove_cv_t<T>, N>; | 
|  | 262 |  | 
|  | 263 | // Deduction guide for variadic constructor. | 
|  | 264 | template <typename T, typename... Us, typename V = std::decay_t<T>, | 
|  | 265 | typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>> | 
|  | 266 | StaticVector(T&&, Us&&...) -> StaticVector<V, 1 + sizeof...(Us)>; | 
|  | 267 |  | 
|  | 268 | // Deduction guide for in-place constructor. | 
|  | 269 | template <typename T, typename... Us> | 
|  | 270 | StaticVector(std::in_place_type_t<T>, Us&&...) -> StaticVector<T, sizeof...(Us)>; | 
|  | 271 |  | 
|  | 272 | template <typename T, size_t N> | 
|  | 273 | template <typename E> | 
|  | 274 | void StaticVector<T, N>::swap(StaticVector& other) { | 
|  | 275 | auto [to, from] = std::make_pair(this, &other); | 
|  | 276 | if (from == this) return; | 
|  | 277 |  | 
|  | 278 | // Assume this vector has fewer elements, so the excess of the other vector will be moved to it. | 
|  | 279 | auto [min, max] = std::make_pair(size(), other.size()); | 
|  | 280 |  | 
|  | 281 | // No elements to swap if moving into an empty vector. | 
|  | 282 | if constexpr (std::is_same_v<E, Empty>) { | 
|  | 283 | assert(min == 0); | 
|  | 284 | } else { | 
|  | 285 | if (min > max) { | 
|  | 286 | std::swap(from, to); | 
|  | 287 | std::swap(min, max); | 
|  | 288 | } | 
|  | 289 |  | 
|  | 290 | // Swap elements [0, min). | 
|  | 291 | std::swap_ranges(begin(), begin() + min, other.begin()); | 
|  | 292 |  | 
|  | 293 | // No elements to move if sizes are equal. | 
|  | 294 | if (min == max) return; | 
|  | 295 | } | 
|  | 296 |  | 
|  | 297 | // Move elements [min, max) and destroy their source for destructor side effects. | 
|  | 298 | const auto [first, last] = std::make_pair(from->begin() + min, from->begin() + max); | 
|  | 299 | std::uninitialized_move(first, last, to->begin() + min); | 
|  | 300 | std::destroy(first, last); | 
|  | 301 |  | 
|  | 302 | std::swap(mSize, other.mSize); | 
|  | 303 | } | 
|  | 304 |  | 
|  | 305 | template <typename T, size_t N> | 
|  | 306 | inline void swap(StaticVector<T, N>& lhs, StaticVector<T, N>& rhs) { | 
|  | 307 | lhs.swap(rhs); | 
|  | 308 | } | 
|  | 309 |  | 
|  | 310 | // TODO: Replace with operator<=> in C++20. | 
|  | 311 | template <typename T, size_t N, size_t M> | 
|  | 312 | inline bool operator==(const StaticVector<T, N>& lhs, const StaticVector<T, M>& rhs) { | 
|  | 313 | return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()); | 
|  | 314 | } | 
|  | 315 |  | 
|  | 316 | template <typename T, size_t N, size_t M> | 
|  | 317 | inline bool operator<(const StaticVector<T, N>& lhs, const StaticVector<T, M>& rhs) { | 
|  | 318 | return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); | 
|  | 319 | } | 
|  | 320 |  | 
|  | 321 | template <typename T, size_t N, size_t M> | 
|  | 322 | inline bool operator>(const StaticVector<T, N>& lhs, const StaticVector<T, M>& rhs) { | 
|  | 323 | return rhs < lhs; | 
|  | 324 | } | 
|  | 325 |  | 
|  | 326 | template <typename T, size_t N, size_t M> | 
|  | 327 | inline bool operator!=(const StaticVector<T, N>& lhs, const StaticVector<T, M>& rhs) { | 
|  | 328 | return !(lhs == rhs); | 
|  | 329 | } | 
|  | 330 |  | 
|  | 331 | template <typename T, size_t N, size_t M> | 
|  | 332 | inline bool operator>=(const StaticVector<T, N>& lhs, const StaticVector<T, M>& rhs) { | 
|  | 333 | return !(lhs < rhs); | 
|  | 334 | } | 
|  | 335 |  | 
|  | 336 | template <typename T, size_t N, size_t M> | 
|  | 337 | inline bool operator<=(const StaticVector<T, N>& lhs, const StaticVector<T, M>& rhs) { | 
|  | 338 | return !(rhs < lhs); | 
|  | 339 | } | 
|  | 340 |  | 
|  | 341 | } // namespace android::ftl |