blob: 990b65ddd6e526268d4418530734947c196ee588 [file] [log] [blame]
mistergc2e75482017-09-19 16:54:40 -04001// Copyright 2017 The Abseil Authors.
2//
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//
60// A `FixedArray` provides a run-time fixed-size array, allocating small arrays
61// inline for efficiency and correctness.
62//
63// Most users should not specify an `inline_elements` argument and let
64// `FixedArray<>` automatically determine the number of elements
65// to store inline based on `sizeof(T)`. If `inline_elements` is specified, the
66// `FixedArray<>` implementation will inline arrays of
67// 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.
87 template <typename Iter>
88 using EnableIfForwardIterator = typename std::enable_if<
89 std::is_convertible<
90 typename std::iterator_traits<Iter>::iterator_category,
91 std::forward_iterator_tag>::value,
92 int>::type;
93
94 public:
95 // For playing nicely with stl:
96 using value_type = T;
97 using iterator = T*;
98 using const_iterator = const T*;
99 using reverse_iterator = std::reverse_iterator<iterator>;
100 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
101 using reference = T&;
102 using const_reference = const T&;
103 using pointer = T*;
104 using const_pointer = const T*;
105 using difference_type = ptrdiff_t;
106 using size_type = size_t;
107
108 static constexpr size_type inline_elements =
109 inlined == kFixedArrayUseDefault
110 ? kInlineBytesDefault / sizeof(value_type)
111 : inlined;
112
Abseil Team87a4c072018-06-25 09:18:19 -0700113 FixedArray(const FixedArray& other)
114 : FixedArray(other.begin(), other.end()) {}
115
Abseil Team6365d172018-01-02 08:53:02 -0800116 FixedArray(FixedArray&& other) noexcept(
117 // clang-format off
118 absl::allocator_is_nothrow<std::allocator<value_type>>::value &&
119 // clang-format on
120 std::is_nothrow_move_constructible<value_type>::value)
Abseil Team87a4c072018-06-25 09:18:19 -0700121 : FixedArray(std::make_move_iterator(other.begin()),
122 std::make_move_iterator(other.end())) {}
Abseil Team6365d172018-01-02 08:53:02 -0800123
mistergc2e75482017-09-19 16:54:40 -0400124 // Creates an array object that can store `n` elements.
125 // Note that trivially constructible elements will be uninitialized.
Abseil Team87a4c072018-06-25 09:18:19 -0700126 explicit FixedArray(size_type n) : rep_(n) {
127 absl::memory_internal::uninitialized_default_construct_n(rep_.begin(),
128 size());
129 }
mistergc2e75482017-09-19 16:54:40 -0400130
131 // Creates an array initialized with `n` copies of `val`.
Abseil Team87a4c072018-06-25 09:18:19 -0700132 FixedArray(size_type n, const value_type& val) : rep_(n) {
133 std::uninitialized_fill_n(data(), size(), val);
134 }
mistergc2e75482017-09-19 16:54:40 -0400135
136 // Creates an array initialized with the elements from the input
137 // range. The array's size will always be `std::distance(first, last)`.
138 // REQUIRES: Iter must be a forward_iterator or better.
139 template <typename Iter, EnableIfForwardIterator<Iter> = 0>
Abseil Team87a4c072018-06-25 09:18:19 -0700140 FixedArray(Iter first, Iter last) : rep_(std::distance(first, last)) {
141 std::uninitialized_copy(first, last, data());
142 }
mistergc2e75482017-09-19 16:54:40 -0400143
Abseil Team8d8dcb02017-09-29 08:44:28 -0700144 // Creates the array from an initializer_list.
mistergc2e75482017-09-19 16:54:40 -0400145 FixedArray(std::initializer_list<T> init_list)
146 : FixedArray(init_list.begin(), init_list.end()) {}
147
Abseil Team87a4c072018-06-25 09:18:19 -0700148 ~FixedArray() noexcept {
149 for (Holder* cur = rep_.begin(); cur != rep_.end(); ++cur) {
150 cur->~Holder();
151 }
152 }
mistergc2e75482017-09-19 16:54:40 -0400153
Abseil Team6365d172018-01-02 08:53:02 -0800154 // Assignments are deleted because they break the invariant that the size of a
155 // `FixedArray` never changes.
156 void operator=(FixedArray&&) = delete;
mistergc2e75482017-09-19 16:54:40 -0400157 void operator=(const FixedArray&) = delete;
158
159 // FixedArray::size()
160 //
161 // Returns the length of the fixed array.
162 size_type size() const { return rep_.size(); }
163
164 // FixedArray::max_size()
165 //
166 // Returns the largest possible value of `std::distance(begin(), end())` for a
167 // `FixedArray<T>`. This is equivalent to the most possible addressable bytes
168 // over the number of bytes taken by T.
169 constexpr size_type max_size() const {
170 return std::numeric_limits<difference_type>::max() / sizeof(value_type);
171 }
172
173 // FixedArray::empty()
174 //
175 // Returns whether or not the fixed array is empty.
176 bool empty() const { return size() == 0; }
177
178 // FixedArray::memsize()
179 //
180 // Returns the memory size of the fixed array in bytes.
181 size_t memsize() const { return size() * sizeof(value_type); }
182
183 // FixedArray::data()
184 //
185 // Returns a const T* pointer to elements of the `FixedArray`. This pointer
186 // can be used to access (but not modify) the contained elements.
187 const_pointer data() const { return AsValue(rep_.begin()); }
188
189 // Overload of FixedArray::data() to return a T* pointer to elements of the
190 // fixed array. This pointer can be used to access and modify the contained
191 // elements.
192 pointer data() { return AsValue(rep_.begin()); }
Abseil Team787891a2018-01-22 13:10:49 -0800193
mistergc2e75482017-09-19 16:54:40 -0400194 // FixedArray::operator[]
195 //
196 // Returns a reference the ith element of the fixed array.
197 // REQUIRES: 0 <= i < size()
198 reference operator[](size_type i) {
199 assert(i < size());
200 return data()[i];
201 }
202
203 // Overload of FixedArray::operator()[] to return a const reference to the
204 // ith element of the fixed array.
205 // REQUIRES: 0 <= i < size()
206 const_reference operator[](size_type i) const {
207 assert(i < size());
208 return data()[i];
209 }
210
211 // FixedArray::at
212 //
213 // Bounds-checked access. Returns a reference to the ith element of the
214 // fiexed array, or throws std::out_of_range
215 reference at(size_type i) {
216 if (ABSL_PREDICT_FALSE(i >= size())) {
217 base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
218 }
219 return data()[i];
220 }
221
222 // Overload of FixedArray::at() to return a const reference to the ith element
223 // of the fixed array.
224 const_reference at(size_type i) const {
Abseil Team5b535402018-04-18 05:56:39 -0700225 if (ABSL_PREDICT_FALSE(i >= size())) {
mistergc2e75482017-09-19 16:54:40 -0400226 base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
227 }
228 return data()[i];
229 }
230
231 // FixedArray::front()
232 //
233 // Returns a reference to the first element of the fixed array.
234 reference front() { return *begin(); }
235
236 // Overload of FixedArray::front() to return a reference to the first element
237 // of a fixed array of const values.
238 const_reference front() const { return *begin(); }
239
240 // FixedArray::back()
241 //
242 // Returns a reference to the last element of the fixed array.
243 reference back() { return *(end() - 1); }
244
245 // Overload of FixedArray::back() to return a reference to the last element
246 // of a fixed array of const values.
247 const_reference back() const { return *(end() - 1); }
248
249 // FixedArray::begin()
250 //
251 // Returns an iterator to the beginning of the fixed array.
252 iterator begin() { return data(); }
253
254 // Overload of FixedArray::begin() to return a const iterator to the
255 // beginning of the fixed array.
256 const_iterator begin() const { return data(); }
257
258 // FixedArray::cbegin()
259 //
260 // Returns a const iterator to the beginning of the fixed array.
261 const_iterator cbegin() const { return begin(); }
262
263 // FixedArray::end()
264 //
265 // Returns an iterator to the end of the fixed array.
266 iterator end() { return data() + size(); }
267
268 // Overload of FixedArray::end() to return a const iterator to the end of the
269 // fixed array.
270 const_iterator end() const { return data() + size(); }
271
272 // FixedArray::cend()
273 //
274 // Returns a const iterator to the end of the fixed array.
275 const_iterator cend() const { return end(); }
276
277 // FixedArray::rbegin()
278 //
279 // Returns a reverse iterator from the end of the fixed array.
280 reverse_iterator rbegin() { return reverse_iterator(end()); }
281
282 // Overload of FixedArray::rbegin() to return a const reverse iterator from
283 // the end of the fixed array.
284 const_reverse_iterator rbegin() const {
285 return const_reverse_iterator(end());
286 }
287
288 // FixedArray::crbegin()
289 //
290 // Returns a const reverse iterator from the end of the fixed array.
291 const_reverse_iterator crbegin() const { return rbegin(); }
292
293 // FixedArray::rend()
294 //
295 // Returns a reverse iterator from the beginning of the fixed array.
296 reverse_iterator rend() { return reverse_iterator(begin()); }
297
298 // Overload of FixedArray::rend() for returning a const reverse iterator
299 // from the beginning of the fixed array.
300 const_reverse_iterator rend() const {
301 return const_reverse_iterator(begin());
302 }
303
304 // FixedArray::crend()
305 //
306 // Returns a reverse iterator from the beginning of the fixed array.
307 const_reverse_iterator crend() const { return rend(); }
308
309 // FixedArray::fill()
310 //
311 // Assigns the given `value` to all elements in the fixed array.
312 void fill(const T& value) { std::fill(begin(), end(), value); }
313
314 // Relational operators. Equality operators are elementwise using
315 // `operator==`, while order operators order FixedArrays lexicographically.
316 friend bool operator==(const FixedArray& lhs, const FixedArray& rhs) {
317 return absl::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
318 }
319
320 friend bool operator!=(const FixedArray& lhs, const FixedArray& rhs) {
321 return !(lhs == rhs);
322 }
323
324 friend bool operator<(const FixedArray& lhs, const FixedArray& rhs) {
325 return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
326 rhs.end());
327 }
328
329 friend bool operator>(const FixedArray& lhs, const FixedArray& rhs) {
330 return rhs < lhs;
331 }
332
333 friend bool operator<=(const FixedArray& lhs, const FixedArray& rhs) {
334 return !(rhs < lhs);
335 }
336
337 friend bool operator>=(const FixedArray& lhs, const FixedArray& rhs) {
338 return !(lhs < rhs);
339 }
340
341 private:
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700342 // Holder
mistergc2e75482017-09-19 16:54:40 -0400343 //
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700344 // Wrapper for holding elements of type T for both the case where T is a
345 // C-style array type and the general case where it is not. This is needed for
346 // construction and destruction of the entire array regardless of how many
347 // dimensions it has.
mistergc2e75482017-09-19 16:54:40 -0400348 //
349 // Maintainer's Note: The simpler solution would be to simply wrap T in a
350 // struct whether it's an array or not: 'struct Holder { T v; };', but
351 // that causes some paranoid diagnostics to misfire about uses of data(),
352 // believing that 'data()' (aka '&rep_.begin().v') is a pointer to a single
353 // element, rather than the packed array that it really is.
354 // e.g.:
355 //
356 // FixedArray<char> buf(1);
357 // sprintf(buf.data(), "foo");
358 //
359 // error: call to int __builtin___sprintf_chk(etc...)
360 // will always overflow destination buffer [-Werror]
361 //
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700362 template <typename OuterT = value_type,
363 typename InnerT = absl::remove_extent_t<OuterT>,
364 size_t InnerN = std::extent<OuterT>::value>
365 struct ArrayHolder {
366 InnerT array[InnerN];
mistergc2e75482017-09-19 16:54:40 -0400367 };
368
Abseil Teamba8d6cf2018-06-28 10:18:50 -0700369 using Holder = absl::conditional_t<std::is_array<value_type>::value,
370 ArrayHolder<value_type>, value_type>;
371
372 static_assert(sizeof(Holder) == sizeof(value_type), "");
373 static_assert(alignof(Holder) == alignof(value_type), "");
374
375 static pointer AsValue(pointer ptr) { return ptr; }
376 static pointer AsValue(ArrayHolder<value_type>* ptr) {
377 return std::addressof(ptr->array);
378 }
mistergc2e75482017-09-19 16:54:40 -0400379
380 // InlineSpace
381 //
382 // Allocate some space, not an array of elements of type T, so that we can
383 // skip calling the T constructors and destructors for space we never use.
384 // How many elements should we store inline?
385 // a. If not specified, use a default of kInlineBytesDefault bytes (This is
386 // currently 256 bytes, which seems small enough to not cause stack overflow
387 // or unnecessary stack pollution, while still allowing stack allocation for
388 // reasonably long character arrays).
389 // b. Never use 0 length arrays (not ISO C++)
390 //
391 template <size_type N, typename = void>
392 class InlineSpace {
393 public:
394 Holder* data() { return reinterpret_cast<Holder*>(space_.data()); }
395 void AnnotateConstruct(size_t n) const { Annotate(n, true); }
396 void AnnotateDestruct(size_t n) const { Annotate(n, false); }
397
398 private:
399#ifndef ADDRESS_SANITIZER
400 void Annotate(size_t, bool) const { }
401#else
402 void Annotate(size_t n, bool creating) const {
403 if (!n) return;
404 const void* bot = &left_redzone_;
405 const void* beg = space_.data();
406 const void* end = space_.data() + n;
407 const void* top = &right_redzone_ + 1;
408 // args: (beg, end, old_mid, new_mid)
409 if (creating) {
410 ANNOTATE_CONTIGUOUS_CONTAINER(beg, top, top, end);
411 ANNOTATE_CONTIGUOUS_CONTAINER(bot, beg, beg, bot);
412 } else {
413 ANNOTATE_CONTIGUOUS_CONTAINER(beg, top, end, top);
414 ANNOTATE_CONTIGUOUS_CONTAINER(bot, beg, bot, beg);
415 }
416 }
417#endif // ADDRESS_SANITIZER
418
419 using Buffer =
420 typename std::aligned_storage<sizeof(Holder), alignof(Holder)>::type;
421
422 ADDRESS_SANITIZER_REDZONE(left_redzone_);
423 std::array<Buffer, N> space_;
424 ADDRESS_SANITIZER_REDZONE(right_redzone_);
425 };
426
427 // specialization when N = 0.
428 template <typename U>
429 class InlineSpace<0, U> {
430 public:
431 Holder* data() { return nullptr; }
432 void AnnotateConstruct(size_t) const {}
433 void AnnotateDestruct(size_t) const {}
434 };
435
436 // Rep
437 //
Abseil Team87a4c072018-06-25 09:18:19 -0700438 // An instance of Rep manages the inline and out-of-line memory for FixedArray
mistergc2e75482017-09-19 16:54:40 -0400439 //
440 class Rep : public InlineSpace<inline_elements> {
441 public:
Abseil Team87a4c072018-06-25 09:18:19 -0700442 explicit Rep(size_type n) : n_(n), p_(MakeHolder(n)) {}
mistergc2e75482017-09-19 16:54:40 -0400443
Abseil Team87a4c072018-06-25 09:18:19 -0700444 ~Rep() noexcept {
mistergc2e75482017-09-19 16:54:40 -0400445 if (IsAllocated(size())) {
Abseil Teamf6eea942018-01-25 10:52:02 -0800446 std::allocator<Holder>().deallocate(p_, n_);
mistergc2e75482017-09-19 16:54:40 -0400447 } else {
448 this->AnnotateDestruct(size());
449 }
450 }
451 Holder* begin() const { return p_; }
452 Holder* end() const { return p_ + n_; }
453 size_type size() const { return n_; }
454
455 private:
456 Holder* MakeHolder(size_type n) {
457 if (IsAllocated(n)) {
Abseil Teamf6eea942018-01-25 10:52:02 -0800458 return std::allocator<Holder>().allocate(n);
mistergc2e75482017-09-19 16:54:40 -0400459 } else {
460 this->AnnotateConstruct(n);
461 return this->data();
462 }
463 }
464
mistergc2e75482017-09-19 16:54:40 -0400465 bool IsAllocated(size_type n) const { return n > inline_elements; }
466
467 const size_type n_;
468 Holder* const p_;
469 };
470
471
472 // Data members
473 Rep rep_;
474};
475
476template <typename T, size_t N>
477constexpr size_t FixedArray<T, N>::inline_elements;
478
479template <typename T, size_t N>
480constexpr size_t FixedArray<T, N>::kInlineBytesDefault;
481
482} // namespace absl
483#endif // ABSL_CONTAINER_FIXED_ARRAY_H_