blob: 62600df05be3612dd87f77d5863107861986a994 [file] [log] [blame]
Abseil Team134496a2018-06-29 14:00:35 -07001// Copyright 2018 The Abseil Authors.
mistergc2e75482017-09-19 16:54:40 -04002//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// -----------------------------------------------------------------------------
16// File: fixed_array.h
17// -----------------------------------------------------------------------------
18//
19// A `FixedArray<T>` represents a non-resizable array of `T` where the length of
20// the array can be determined at run-time. It is a good replacement for
21// non-standard and deprecated uses of `alloca()` and variable length arrays
22// within the GCC extension. (See
23// https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html).
24//
25// `FixedArray` allocates small arrays inline, keeping performance fast by
26// avoiding heap operations. It also helps reduce the chances of
27// accidentally overflowing your stack if large input is passed to
28// your function.
29
30#ifndef ABSL_CONTAINER_FIXED_ARRAY_H_
31#define ABSL_CONTAINER_FIXED_ARRAY_H_
32
33#include <algorithm>
34#include <array>
35#include <cassert>
36#include <cstddef>
37#include <initializer_list>
38#include <iterator>
39#include <limits>
40#include <memory>
41#include <new>
42#include <type_traits>
43
44#include "absl/algorithm/algorithm.h"
45#include "absl/base/dynamic_annotations.h"
46#include "absl/base/internal/throw_delegate.h"
47#include "absl/base/macros.h"
48#include "absl/base/optimization.h"
49#include "absl/base/port.h"
Abseil Team6365d172018-01-02 08:53:02 -080050#include "absl/memory/memory.h"
mistergc2e75482017-09-19 16:54:40 -040051
52namespace absl {
53
54constexpr static auto kFixedArrayUseDefault = static_cast<size_t>(-1);
55
56// -----------------------------------------------------------------------------
57// FixedArray
58// -----------------------------------------------------------------------------
59//
Abseil Team134496a2018-06-29 14:00:35 -070060// A `FixedArray` provides a run-time fixed-size array, allocating a small array
61// inline for efficiency.
mistergc2e75482017-09-19 16:54:40 -040062//
63// Most users should not specify an `inline_elements` argument and let
Abseil Team134496a2018-06-29 14:00:35 -070064// `FixedArray` automatically determine the number of elements
mistergc2e75482017-09-19 16:54:40 -040065// to store inline based on `sizeof(T)`. If `inline_elements` is specified, the
Abseil Team134496a2018-06-29 14:00:35 -070066// `FixedArray` implementation will use inline storage for arrays with a
mistergc2e75482017-09-19 16:54:40 -040067// length <= `inline_elements`.
68//
69// Note that a `FixedArray` constructed with a `size_type` argument will
70// default-initialize its values by leaving trivially constructible types
71// uninitialized (e.g. int, int[4], double), and others default-constructed.
72// This matches the behavior of c-style arrays and `std::array`, but not
73// `std::vector`.
74//
75// Note that `FixedArray` does not provide a public allocator; if it requires a
76// heap allocation, it will do so with global `::operator new[]()` and
77// `::operator delete[]()`, even if T provides class-scope overrides for these
78// operators.
79template <typename T, size_t inlined = kFixedArrayUseDefault>
80class FixedArray {
Abseil Teamba8d6cf2018-06-28 10:18:50 -070081 static_assert(!std::is_array<T>::value || std::extent<T>::value > 0,
82 "Arrays with unknown bounds cannot be used with FixedArray.");
mistergc2e75482017-09-19 16:54:40 -040083 static constexpr size_t kInlineBytesDefault = 256;
84
85 // std::iterator_traits isn't guaranteed to be SFINAE-friendly until C++17,
86 // but this seems to be mostly pedantic.
Abseil Team134496a2018-06-29 14:00:35 -070087 template <typename Iterator>
88 using EnableIfForwardIterator = absl::enable_if_t<std::is_convertible<
89 typename std::iterator_traits<Iterator>::iterator_category,
90 std::forward_iterator_tag>::value>;
mistergc2e75482017-09-19 16:54:40 -040091
92 public:
mistergc2e75482017-09-19 16:54:40 -040093 using value_type = T;
94 using iterator = T*;
95 using const_iterator = const T*;
96 using reverse_iterator = std::reverse_iterator<iterator>;
97 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
98 using reference = T&;
99 using const_reference = const T&;
100 using pointer = T*;
101 using const_pointer = const T*;
102 using difference_type = ptrdiff_t;
103 using size_type = size_t;
104
105 static constexpr size_type inline_elements =
106 inlined == kFixedArrayUseDefault
107 ? kInlineBytesDefault / sizeof(value_type)
108 : inlined;
109
Abseil Team87a4c072018-06-25 09:18:19 -0700110 FixedArray(const FixedArray& other)
111 : FixedArray(other.begin(), other.end()) {}
112
Abseil Team6365d172018-01-02 08:53:02 -0800113 FixedArray(FixedArray&& other) noexcept(
Abseil Team134496a2018-06-29 14:00:35 -0700114 absl::conjunction<absl::allocator_is_nothrow<std::allocator<value_type>>,
115 std::is_nothrow_move_constructible<value_type>>::value)
Abseil Team87a4c072018-06-25 09:18:19 -0700116 : FixedArray(std::make_move_iterator(other.begin()),
117 std::make_move_iterator(other.end())) {}
Abseil Team6365d172018-01-02 08:53:02 -0800118
mistergc2e75482017-09-19 16:54:40 -0400119 // Creates an array object that can store `n` elements.
120 // Note that trivially constructible elements will be uninitialized.
Abseil Team134496a2018-06-29 14:00:35 -0700121 explicit FixedArray(size_type n) : storage_(n) {
122 absl::memory_internal::uninitialized_default_construct_n(storage_.begin(),
Abseil Team87a4c072018-06-25 09:18:19 -0700123 size());
124 }
mistergc2e75482017-09-19 16:54:40 -0400125
126 // Creates an array initialized with `n` copies of `val`.
Abseil Team134496a2018-06-29 14:00:35 -0700127 FixedArray(size_type n, const value_type& val) : storage_(n) {
Abseil Team87a4c072018-06-25 09:18:19 -0700128 std::uninitialized_fill_n(data(), size(), val);
129 }
mistergc2e75482017-09-19 16:54:40 -0400130
131 // Creates an array initialized with the elements from the input
132 // range. The array's size will always be `std::distance(first, last)`.
Abseil Team134496a2018-06-29 14:00:35 -0700133 // REQUIRES: Iterator must be a forward_iterator or better.
134 template <typename Iterator, EnableIfForwardIterator<Iterator>* = nullptr>
135 FixedArray(Iterator first, Iterator last)
136 : storage_(std::distance(first, last)) {
Abseil Team87a4c072018-06-25 09:18:19 -0700137 std::uninitialized_copy(first, last, data());
138 }
mistergc2e75482017-09-19 16:54:40 -0400139
Abseil Team134496a2018-06-29 14:00:35 -0700140 FixedArray(std::initializer_list<value_type> init_list)
mistergc2e75482017-09-19 16:54:40 -0400141 : FixedArray(init_list.begin(), init_list.end()) {}
142
Abseil Team87a4c072018-06-25 09:18:19 -0700143 ~FixedArray() noexcept {
Abseil Team134496a2018-06-29 14:00:35 -0700144 for (const StorageElement& cur : storage_) {
145 cur.~StorageElement();
Abseil Team87a4c072018-06-25 09:18:19 -0700146 }
147 }
mistergc2e75482017-09-19 16:54:40 -0400148
Abseil Team6365d172018-01-02 08:53:02 -0800149 // Assignments are deleted because they break the invariant that the size of a
150 // `FixedArray` never changes.
151 void operator=(FixedArray&&) = delete;
mistergc2e75482017-09-19 16:54:40 -0400152 void operator=(const FixedArray&) = delete;
153
154 // FixedArray::size()
155 //
156 // Returns the length of the fixed array.
Abseil Team134496a2018-06-29 14:00:35 -0700157 size_type size() const { return storage_.size(); }
mistergc2e75482017-09-19 16:54:40 -0400158
159 // FixedArray::max_size()
160 //
161 // Returns the largest possible value of `std::distance(begin(), end())` for a
162 // `FixedArray<T>`. This is equivalent to the most possible addressable bytes
163 // over the number of bytes taken by T.
164 constexpr size_type max_size() const {
165 return std::numeric_limits<difference_type>::max() / sizeof(value_type);
166 }
167
168 // FixedArray::empty()
169 //
170 // Returns whether or not the fixed array is empty.
171 bool empty() const { return size() == 0; }
172
173 // FixedArray::memsize()
174 //
175 // Returns the memory size of the fixed array in bytes.
176 size_t memsize() const { return size() * sizeof(value_type); }
177
178 // FixedArray::data()
179 //
180 // Returns a const T* pointer to elements of the `FixedArray`. This pointer
181 // can be used to access (but not modify) the contained elements.
Abseil Team134496a2018-06-29 14:00:35 -0700182 const_pointer data() const { return AsValueType(storage_.begin()); }
mistergc2e75482017-09-19 16:54:40 -0400183
184 // Overload of FixedArray::data() to return a T* pointer to elements of the
185 // fixed array. This pointer can be used to access and modify the contained
186 // elements.
Abseil Team134496a2018-06-29 14:00:35 -0700187 pointer data() { return AsValueType(storage_.begin()); }
Abseil Team787891a2018-01-22 13:10:49 -0800188
mistergc2e75482017-09-19 16:54:40 -0400189 // FixedArray::operator[]
190 //
191 // Returns a reference the ith element of the fixed array.
192 // REQUIRES: 0 <= i < size()
193 reference operator[](size_type i) {
194 assert(i < size());
195 return data()[i];
196 }
197
198 // Overload of FixedArray::operator()[] to return a const reference to the
199 // ith element of the fixed array.
200 // REQUIRES: 0 <= i < size()
201 const_reference operator[](size_type i) const {
202 assert(i < size());
203 return data()[i];
204 }
205
206 // FixedArray::at
207 //
208 // Bounds-checked access. Returns a reference to the ith element of the
209 // fiexed array, or throws std::out_of_range
210 reference at(size_type i) {
211 if (ABSL_PREDICT_FALSE(i >= size())) {
212 base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
213 }
214 return data()[i];
215 }
216
217 // Overload of FixedArray::at() to return a const reference to the ith element
218 // of the fixed array.
219 const_reference at(size_type i) const {
Abseil Team5b535402018-04-18 05:56:39 -0700220 if (ABSL_PREDICT_FALSE(i >= size())) {
mistergc2e75482017-09-19 16:54:40 -0400221 base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
222 }
223 return data()[i];
224 }
225
226 // FixedArray::front()
227 //
228 // Returns a reference to the first element of the fixed array.
229 reference front() { return *begin(); }
230
231 // Overload of FixedArray::front() to return a reference to the first element
232 // of a fixed array of const values.
233 const_reference front() const { return *begin(); }
234
235 // FixedArray::back()
236 //
237 // Returns a reference to the last element of the fixed array.
238 reference back() { return *(end() - 1); }
239
240 // Overload of FixedArray::back() to return a reference to the last element
241 // of a fixed array of const values.
242 const_reference back() const { return *(end() - 1); }
243
244 // FixedArray::begin()
245 //
246 // Returns an iterator to the beginning of the fixed array.
247 iterator begin() { return data(); }
248
249 // Overload of FixedArray::begin() to return a const iterator to the
250 // beginning of the fixed array.
251 const_iterator begin() const { return data(); }
252
253 // FixedArray::cbegin()
254 //
255 // Returns a const iterator to the beginning of the fixed array.
256 const_iterator cbegin() const { return begin(); }
257
258 // FixedArray::end()
259 //
260 // Returns an iterator to the end of the fixed array.
261 iterator end() { return data() + size(); }
262
263 // Overload of FixedArray::end() to return a const iterator to the end of the
264 // fixed array.
265 const_iterator end() const { return data() + size(); }
266
267 // FixedArray::cend()
268 //
269 // Returns a const iterator to the end of the fixed array.
270 const_iterator cend() const { return end(); }
271
272 // FixedArray::rbegin()
273 //
274 // Returns a reverse iterator from the end of the fixed array.
275 reverse_iterator rbegin() { return reverse_iterator(end()); }
276
277 // Overload of FixedArray::rbegin() to return a const reverse iterator from
278 // the end of the fixed array.
279 const_reverse_iterator rbegin() const {
280 return const_reverse_iterator(end());
281 }
282
283 // FixedArray::crbegin()
284 //
285 // Returns a const reverse iterator from the end of the fixed array.
286 const_reverse_iterator crbegin() const { return rbegin(); }
287
288 // FixedArray::rend()
289 //
290 // Returns a reverse iterator from the beginning of the fixed array.
291 reverse_iterator rend() { return reverse_iterator(begin()); }
292
293 // Overload of FixedArray::rend() for returning a const reverse iterator
294 // from the beginning of the fixed array.
295 const_reverse_iterator rend() const {
296 return const_reverse_iterator(begin());
297 }
298
299 // FixedArray::crend()
300 //
301 // Returns a reverse iterator from the beginning of the fixed array.
302 const_reverse_iterator crend() const { return rend(); }
303
304 // FixedArray::fill()
305 //
306 // Assigns the given `value` to all elements in the fixed array.
Abseil Team134496a2018-06-29 14:00:35 -0700307 void fill(const value_type& val) { std::fill(begin(), end(), val); }
mistergc2e75482017-09-19 16:54:40 -0400308
309 // Relational operators. Equality operators are elementwise using
310 // `operator==`, while order operators order FixedArrays lexicographically.
311 friend bool operator==(const FixedArray& lhs, const FixedArray& rhs) {
312 return absl::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
313 }
314
315 friend bool operator!=(const FixedArray& lhs, const FixedArray& rhs) {
316 return !(lhs == rhs);
317 }
318
319 friend bool operator<(const FixedArray& lhs, const FixedArray& rhs) {
320 return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
321 rhs.end());
322 }
323
324 friend bool operator>(const FixedArray& lhs, const FixedArray& rhs) {
325 return rhs < lhs;
326 }
327
328 friend bool operator<=(const FixedArray& lhs, const FixedArray& rhs) {
329 return !(rhs < lhs);
330 }
331
332 friend bool operator>=(const FixedArray& lhs, const FixedArray& rhs) {
333 return !(lhs < rhs);
334 }
335
336 private:
Abseil Team134496a2018-06-29 14:00:35 -0700337 // StorageElement
mistergc2e75482017-09-19 16:54:40 -0400338 //
Abseil Team134496a2018-06-29 14:00:35 -0700339 // For FixedArrays with a C-style-array value_type, StorageElement is a POD
340 // wrapper struct called StorageElementWrapper that holds the value_type
341 // instance inside. This is needed for construction and destruction of the
342 // entire array regardless of how many dimensions it has. For all other cases,
343 // StorageElement is just an alias of value_type.
mistergc2e75482017-09-19 16:54:40 -0400344 //
Abseil Team134496a2018-06-29 14:00:35 -0700345 // Maintainer's Note: The simpler solution would be to simply wrap value_type
346 // in a struct whether it's an array or not. That causes some paranoid
347 // diagnostics to misfire, believing that 'data()' returns a pointer to a
348 // single element, rather than the packed array that it really is.
mistergc2e75482017-09-19 16:54:40 -0400349 // e.g.:
350 //
351 // FixedArray<char> buf(1);
352 // sprintf(buf.data(), "foo");
353 //
354 // error: call to int __builtin___sprintf_chk(etc...)
355 // will always overflow destination buffer [-Werror]
356 //
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700357 template <typename OuterT = value_type,
358 typename InnerT = absl::remove_extent_t<OuterT>,
359 size_t InnerN = std::extent<OuterT>::value>
Abseil Team134496a2018-06-29 14:00:35 -0700360 struct StorageElementWrapper {
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700361 InnerT array[InnerN];
mistergc2e75482017-09-19 16:54:40 -0400362 };
363
Abseil Team134496a2018-06-29 14:00:35 -0700364 using StorageElement =
365 absl::conditional_t<std::is_array<value_type>::value,
366 StorageElementWrapper<value_type>, value_type>;
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700367
Abseil Team134496a2018-06-29 14:00:35 -0700368 static pointer AsValueType(pointer ptr) { return ptr; }
369 static pointer AsValueType(StorageElementWrapper<value_type>* ptr) {
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700370 return std::addressof(ptr->array);
371 }
mistergc2e75482017-09-19 16:54:40 -0400372
Abseil Team134496a2018-06-29 14:00:35 -0700373 static_assert(sizeof(StorageElement) == sizeof(value_type), "");
374 static_assert(alignof(StorageElement) == alignof(value_type), "");
mistergc2e75482017-09-19 16:54:40 -0400375
Abseil Team134496a2018-06-29 14:00:35 -0700376 struct NonEmptyInlinedStorage {
377 using StorageElementBuffer =
378 absl::aligned_storage_t<sizeof(StorageElement),
379 alignof(StorageElement)>;
380 StorageElement* data() {
381 return reinterpret_cast<StorageElement*>(inlined_storage_.data());
mistergc2e75482017-09-19 16:54:40 -0400382 }
Abseil Team134496a2018-06-29 14:00:35 -0700383
384#ifdef ADDRESS_SANITIZER
385 void* RedzoneBegin() { return &redzone_begin_; }
386 void* RedzoneEnd() { return &redzone_end_ + 1; }
mistergc2e75482017-09-19 16:54:40 -0400387#endif // ADDRESS_SANITIZER
388
Abseil Team134496a2018-06-29 14:00:35 -0700389 void AnnotateConstruct(size_t);
390 void AnnotateDestruct(size_t);
mistergc2e75482017-09-19 16:54:40 -0400391
Abseil Team134496a2018-06-29 14:00:35 -0700392 ADDRESS_SANITIZER_REDZONE(redzone_begin_);
393 std::array<StorageElementBuffer, inline_elements> inlined_storage_;
394 ADDRESS_SANITIZER_REDZONE(redzone_end_);
mistergc2e75482017-09-19 16:54:40 -0400395 };
396
Abseil Team134496a2018-06-29 14:00:35 -0700397 struct EmptyInlinedStorage {
398 StorageElement* data() { return nullptr; }
399 void AnnotateConstruct(size_t) {}
400 void AnnotateDestruct(size_t) {}
mistergc2e75482017-09-19 16:54:40 -0400401 };
402
Abseil Team134496a2018-06-29 14:00:35 -0700403 using InlinedStorage =
404 absl::conditional_t<inline_elements == 0, EmptyInlinedStorage,
405 NonEmptyInlinedStorage>;
mistergc2e75482017-09-19 16:54:40 -0400406
Abseil Team134496a2018-06-29 14:00:35 -0700407 // Storage
408 //
409 // An instance of Storage manages the inline and out-of-line memory for
410 // instances of FixedArray. This guarantees that even when construction of
411 // individual elements fails in the FixedArray constructor body, the
412 // destructor for Storage will still be called and out-of-line memory will be
413 // properly deallocated.
414 //
415 class Storage : public InlinedStorage {
416 public:
417 explicit Storage(size_type n) : data_(CreateStorage(n)), size_(n) {}
418 ~Storage() noexcept {
419 if (UsingInlinedStorage(size())) {
mistergc2e75482017-09-19 16:54:40 -0400420 this->AnnotateDestruct(size());
Abseil Team134496a2018-06-29 14:00:35 -0700421 } else {
422 std::allocator<StorageElement>().deallocate(begin(), size());
mistergc2e75482017-09-19 16:54:40 -0400423 }
424 }
Abseil Team134496a2018-06-29 14:00:35 -0700425
426 size_type size() const { return size_; }
427 StorageElement* begin() const { return data_; }
428 StorageElement* end() const { return begin() + size(); }
mistergc2e75482017-09-19 16:54:40 -0400429
430 private:
Abseil Team134496a2018-06-29 14:00:35 -0700431 static bool UsingInlinedStorage(size_type n) {
432 return n <= inline_elements;
433 }
434
435 StorageElement* CreateStorage(size_type n) {
436 if (UsingInlinedStorage(n)) {
mistergc2e75482017-09-19 16:54:40 -0400437 this->AnnotateConstruct(n);
Abseil Team134496a2018-06-29 14:00:35 -0700438 return InlinedStorage::data();
439 } else {
440 return std::allocator<StorageElement>().allocate(n);
mistergc2e75482017-09-19 16:54:40 -0400441 }
442 }
443
Abseil Team134496a2018-06-29 14:00:35 -0700444 StorageElement* const data_;
445 const size_type size_;
mistergc2e75482017-09-19 16:54:40 -0400446 };
447
Abseil Team134496a2018-06-29 14:00:35 -0700448 const Storage storage_;
mistergc2e75482017-09-19 16:54:40 -0400449};
450
451template <typename T, size_t N>
452constexpr size_t FixedArray<T, N>::inline_elements;
453
454template <typename T, size_t N>
455constexpr size_t FixedArray<T, N>::kInlineBytesDefault;
456
Abseil Team134496a2018-06-29 14:00:35 -0700457template <typename T, size_t N>
458void FixedArray<T, N>::NonEmptyInlinedStorage::AnnotateConstruct(size_t n) {
459#ifdef ADDRESS_SANITIZER
460 if (!n) return;
461 ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), RedzoneEnd(), data() + n);
462 ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), data(), RedzoneBegin());
463#endif // ADDRESS_SANITIZER
464 static_cast<void>(n); // Mark used when not in asan mode
465}
466
467template <typename T, size_t N>
468void FixedArray<T, N>::NonEmptyInlinedStorage::AnnotateDestruct(size_t n) {
469#ifdef ADDRESS_SANITIZER
470 if (!n) return;
471 ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), data() + n, RedzoneEnd());
472 ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), RedzoneBegin(), data());
473#endif // ADDRESS_SANITIZER
474 static_cast<void>(n); // Mark used when not in asan mode
475}
476
mistergc2e75482017-09-19 16:54:40 -0400477} // namespace absl
478#endif // ABSL_CONTAINER_FIXED_ARRAY_H_