blob: cecec7f8736d3b3c4d1dc19fe5f5c527242a8de6 [file] [log] [blame]
Dominik Laskowski0bacf272020-10-22 14:08:27 -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
19#include <ftl/ArrayTraits.h>
20#include <ftl/StaticVector.h>
21
22#include <algorithm>
23#include <iterator>
24#include <type_traits>
25#include <utility>
26#include <variant>
27#include <vector>
28
29namespace android::ftl {
30
31template <typename>
32struct IsSmallVector;
33
34// ftl::StaticVector that promotes to std::vector when full. SmallVector is a drop-in replacement
35// for std::vector with statically allocated storage for N elements, whose goal is to improve run
36// time by avoiding heap allocation and increasing probability of cache hits. The standard API is
37// augmented by an unstable_erase operation that does not preserve order, and a replace operation
38// that destructively emplaces.
39//
40// SmallVector<T, 0> is a specialization that thinly wraps std::vector.
41//
42// Example usage:
43//
44// ftl::SmallVector<char, 3> vector;
45// assert(vector.empty());
46// assert(!vector.dynamic());
47//
48// vector = {'a', 'b', 'c'};
49// assert(vector.size() == 3u);
50// assert(!vector.dynamic());
51//
52// vector.push_back('d');
53// assert(vector.dynamic());
54//
55// vector.unstable_erase(vector.begin());
56// assert(vector == (ftl::SmallVector{'d', 'b', 'c'}));
57//
58// vector.pop_back();
59// assert(vector.back() == 'b');
60// assert(vector.dynamic());
61//
62// const char array[] = "hi";
63// vector = ftl::SmallVector(array);
64// assert(vector == (ftl::SmallVector{'h', 'i', '\0'}));
65// assert(!vector.dynamic());
66//
67template <typename T, size_t N>
68class SmallVector final : ArrayTraits<T>, ArrayComparators<SmallVector> {
69 using Static = StaticVector<T, N>;
70 using Dynamic = SmallVector<T, 0>;
71
72 // TODO: Replace with std::remove_cvref_t in C++20.
73 template <typename U>
74 using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<U>>;
75
76public:
77 FTL_ARRAY_TRAIT(T, value_type);
78 FTL_ARRAY_TRAIT(T, size_type);
79 FTL_ARRAY_TRAIT(T, difference_type);
80
81 FTL_ARRAY_TRAIT(T, pointer);
82 FTL_ARRAY_TRAIT(T, reference);
83 FTL_ARRAY_TRAIT(T, iterator);
84 FTL_ARRAY_TRAIT(T, reverse_iterator);
85
86 FTL_ARRAY_TRAIT(T, const_pointer);
87 FTL_ARRAY_TRAIT(T, const_reference);
88 FTL_ARRAY_TRAIT(T, const_iterator);
89 FTL_ARRAY_TRAIT(T, const_reverse_iterator);
90
91 // Creates an empty vector.
92 SmallVector() = default;
93
94 // Constructs at most N elements. See StaticVector for underlying constructors.
95 template <typename Arg, typename... Args,
96 typename = std::enable_if_t<!IsSmallVector<remove_cvref_t<Arg>>{}>>
97 SmallVector(Arg&& arg, Args&&... args)
98 : mVector(std::in_place_type<Static>, std::forward<Arg>(arg),
99 std::forward<Args>(args)...) {}
100
101 // Copies at most N elements from a smaller convertible vector.
102 template <typename U, size_t M, typename = std::enable_if_t<M <= N>>
103 SmallVector(const SmallVector<U, M>& other)
104 : SmallVector(IteratorRange, other.begin(), other.end()) {}
105
106 void swap(SmallVector& other) { mVector.swap(other.mVector); }
107
108 // Returns whether the vector is backed by static or dynamic storage.
109 bool dynamic() const { return std::holds_alternative<Dynamic>(mVector); }
110
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700111 // Avoid std::visit as it generates a dispatch table.
112#define DISPATCH(T, F, ...) \
113 T F() __VA_ARGS__ { \
114 return dynamic() ? std::get<Dynamic>(mVector).F() : std::get<Static>(mVector).F(); \
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700115 }
116
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700117 DISPATCH(size_type, max_size, const)
118 DISPATCH(size_type, size, const)
119 DISPATCH(bool, empty, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700120
121 // noexcept to suppress warning about zero variadic macro arguments.
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700122 DISPATCH(iterator, begin, noexcept)
123 DISPATCH(const_iterator, begin, const)
124 DISPATCH(const_iterator, cbegin, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700125
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700126 DISPATCH(iterator, end, noexcept)
127 DISPATCH(const_iterator, end, const)
128 DISPATCH(const_iterator, cend, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700129
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700130 DISPATCH(reverse_iterator, rbegin, noexcept)
131 DISPATCH(const_reverse_iterator, rbegin, const)
132 DISPATCH(const_reverse_iterator, crbegin, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700133
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700134 DISPATCH(reverse_iterator, rend, noexcept)
135 DISPATCH(const_reverse_iterator, rend, const)
136 DISPATCH(const_reverse_iterator, crend, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700137
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700138 DISPATCH(iterator, last, noexcept)
139 DISPATCH(const_iterator, last, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700140
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700141 DISPATCH(reference, front, noexcept)
142 DISPATCH(const_reference, front, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700143
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700144 DISPATCH(reference, back, noexcept)
145 DISPATCH(const_reference, back, const)
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700146
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700147#undef DISPATCH
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700148
149 reference operator[](size_type i) {
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700150 return dynamic() ? std::get<Dynamic>(mVector)[i] : std::get<Static>(mVector)[i];
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700151 }
152
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700153 const_reference operator[](size_type i) const { return const_cast<SmallVector&>(*this)[i]; }
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700154
155 // Replaces an element, and returns a reference to it. The iterator must be dereferenceable, so
156 // replacing at end() is erroneous.
157 //
158 // The element is emplaced via move constructor, so type T does not need to define copy/move
159 // assignment, e.g. its data members may be const.
160 //
161 // The arguments may directly or indirectly refer to the element being replaced.
162 //
163 // Iterators to the replaced element point to its replacement, and others remain valid.
164 //
165 template <typename... Args>
166 reference replace(const_iterator it, Args&&... args) {
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700167 if (dynamic()) {
168 return std::get<Dynamic>(mVector).replace(it, std::forward<Args>(args)...);
169 } else {
170 return std::get<Static>(mVector).replace(it, std::forward<Args>(args)...);
171 }
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700172 }
173
174 // Appends an element, and returns a reference to it.
175 //
176 // If the vector reaches its static or dynamic capacity, then all iterators are invalidated.
177 // Otherwise, only the end() iterator is invalidated.
178 //
179 template <typename... Args>
180 reference emplace_back(Args&&... args) {
181 constexpr auto insertStatic = &Static::template emplace_back<Args...>;
182 constexpr auto insertDynamic = &Dynamic::template emplace_back<Args...>;
183 return *insert<insertStatic, insertDynamic>(std::forward<Args>(args)...);
184 }
185
186 // Appends an element.
187 //
188 // If the vector reaches its static or dynamic capacity, then all iterators are invalidated.
189 // Otherwise, only the end() iterator is invalidated.
190 //
191 void push_back(const value_type& v) {
192 constexpr auto insertStatic =
193 static_cast<bool (Static::*)(const value_type&)>(&Static::push_back);
194 constexpr auto insertDynamic =
195 static_cast<bool (Dynamic::*)(const value_type&)>(&Dynamic::push_back);
196 insert<insertStatic, insertDynamic>(v);
197 }
198
199 void push_back(value_type&& v) {
200 constexpr auto insertStatic =
201 static_cast<bool (Static::*)(value_type&&)>(&Static::push_back);
202 constexpr auto insertDynamic =
203 static_cast<bool (Dynamic::*)(value_type&&)>(&Dynamic::push_back);
204 insert<insertStatic, insertDynamic>(std::move(v));
205 }
206
207 // Removes the last element. The vector must not be empty, or the call is erroneous.
208 //
209 // The last() and end() iterators are invalidated.
210 //
211 void pop_back() {
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700212 if (dynamic()) {
213 std::get<Dynamic>(mVector).pop_back();
214 } else {
215 std::get<Static>(mVector).pop_back();
216 }
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700217 }
218
219 // Erases an element, but does not preserve order. Rather than shifting subsequent elements,
220 // this moves the last element to the slot of the erased element.
221 //
222 // The last() and end() iterators, as well as those to the erased element, are invalidated.
223 //
224 void unstable_erase(iterator it) {
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700225 if (dynamic()) {
226 std::get<Dynamic>(mVector).unstable_erase(it);
227 } else {
228 std::get<Static>(mVector).unstable_erase(it);
229 }
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700230 }
231
232private:
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700233 template <auto insertStatic, auto insertDynamic, typename... Args>
234 auto insert(Args&&... args) {
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700235 if (Dynamic* const vector = std::get_if<Dynamic>(&mVector)) {
236 return (vector->*insertDynamic)(std::forward<Args>(args)...);
237 }
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700238
Dominik Laskowski534b2a22020-10-26 16:31:47 -0700239 auto& vector = std::get<Static>(mVector);
240 if (vector.full()) {
241 return (promote(vector).*insertDynamic)(std::forward<Args>(args)...);
242 } else {
243 return (vector.*insertStatic)(std::forward<Args>(args)...);
244 }
Dominik Laskowski0bacf272020-10-22 14:08:27 -0700245 }
246
247 Dynamic& promote(Static& staticVector) {
248 assert(staticVector.full());
249
250 // Allocate double capacity to reduce probability of reallocation.
251 Dynamic vector;
252 vector.reserve(Static::max_size() * 2);
253 std::move(staticVector.begin(), staticVector.end(), std::back_inserter(vector));
254
255 return mVector.template emplace<Dynamic>(std::move(vector));
256 }
257
258 std::variant<Static, Dynamic> mVector;
259};
260
261// Partial specialization without static storage.
262template <typename T>
263class SmallVector<T, 0> final : ArrayTraits<T>,
264 ArrayIterators<SmallVector<T, 0>, T>,
265 std::vector<T> {
266 using ArrayTraits<T>::construct_at;
267
268 using Iter = ArrayIterators<SmallVector, T>;
269 using Impl = std::vector<T>;
270
271 friend Iter;
272
273public:
274 FTL_ARRAY_TRAIT(T, value_type);
275 FTL_ARRAY_TRAIT(T, size_type);
276 FTL_ARRAY_TRAIT(T, difference_type);
277
278 FTL_ARRAY_TRAIT(T, pointer);
279 FTL_ARRAY_TRAIT(T, reference);
280 FTL_ARRAY_TRAIT(T, iterator);
281 FTL_ARRAY_TRAIT(T, reverse_iterator);
282
283 FTL_ARRAY_TRAIT(T, const_pointer);
284 FTL_ARRAY_TRAIT(T, const_reference);
285 FTL_ARRAY_TRAIT(T, const_iterator);
286 FTL_ARRAY_TRAIT(T, const_reverse_iterator);
287
288 using Impl::Impl;
289
290 using Impl::empty;
291 using Impl::max_size;
292 using Impl::size;
293
294 using Impl::reserve;
295
296 // std::vector iterators are not necessarily raw pointers.
297 iterator begin() { return Impl::data(); }
298 iterator end() { return Impl::data() + size(); }
299
300 using Iter::begin;
301 using Iter::end;
302
303 using Iter::cbegin;
304 using Iter::cend;
305
306 using Iter::rbegin;
307 using Iter::rend;
308
309 using Iter::crbegin;
310 using Iter::crend;
311
312 using Iter::last;
313
314 using Iter::back;
315 using Iter::front;
316
317 using Iter::operator[];
318
319 template <typename... Args>
320 reference replace(const_iterator it, Args&&... args) {
321 value_type element{std::forward<Args>(args)...};
322 std::destroy_at(it);
323 // This is only safe because exceptions are disabled.
324 return *construct_at(it, std::move(element));
325 }
326
327 template <typename... Args>
328 iterator emplace_back(Args&&... args) {
329 return &Impl::emplace_back(std::forward<Args>(args)...);
330 }
331
332 bool push_back(const value_type& v) {
333 Impl::push_back(v);
334 return true;
335 }
336
337 bool push_back(value_type&& v) {
338 Impl::push_back(std::move(v));
339 return true;
340 }
341
342 using Impl::pop_back;
343
344 void unstable_erase(iterator it) {
345 if (it != last()) std::iter_swap(it, last());
346 pop_back();
347 }
348
349 void swap(SmallVector& other) { Impl::swap(other); }
350};
351
352template <typename>
353struct IsSmallVector : std::false_type {};
354
355template <typename T, size_t N>
356struct IsSmallVector<SmallVector<T, N>> : std::true_type {};
357
358// Deduction guide for array constructor.
359template <typename T, size_t N>
360SmallVector(T (&)[N]) -> SmallVector<std::remove_cv_t<T>, N>;
361
362// Deduction guide for variadic constructor.
363template <typename T, typename... Us, typename V = std::decay_t<T>,
364 typename = std::enable_if_t<(std::is_constructible_v<V, Us> && ...)>>
365SmallVector(T&&, Us&&...) -> SmallVector<V, 1 + sizeof...(Us)>;
366
367// Deduction guide for in-place constructor.
368template <typename T, typename... Us>
369SmallVector(std::in_place_type_t<T>, Us&&...) -> SmallVector<T, sizeof...(Us)>;
370
371// Deduction guide for StaticVector conversion.
372template <typename T, size_t N>
373SmallVector(StaticVector<T, N>&&) -> SmallVector<T, N>;
374
375template <typename T, size_t N>
376inline void swap(SmallVector<T, N>& lhs, SmallVector<T, N>& rhs) {
377 lhs.swap(rhs);
378}
379
380} // namespace android::ftl