blob: 295f01088d2182709d7947474ec60a58d22e2bb7 [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 {
81 static constexpr size_t kInlineBytesDefault = 256;
82
83 // std::iterator_traits isn't guaranteed to be SFINAE-friendly until C++17,
84 // but this seems to be mostly pedantic.
85 template <typename Iter>
86 using EnableIfForwardIterator = typename std::enable_if<
87 std::is_convertible<
88 typename std::iterator_traits<Iter>::iterator_category,
89 std::forward_iterator_tag>::value,
90 int>::type;
91
92 public:
93 // For playing nicely with stl:
94 using value_type = T;
95 using iterator = T*;
96 using const_iterator = const T*;
97 using reverse_iterator = std::reverse_iterator<iterator>;
98 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
99 using reference = T&;
100 using const_reference = const T&;
101 using pointer = T*;
102 using const_pointer = const T*;
103 using difference_type = ptrdiff_t;
104 using size_type = size_t;
105
106 static constexpr size_type inline_elements =
107 inlined == kFixedArrayUseDefault
108 ? kInlineBytesDefault / sizeof(value_type)
109 : inlined;
110
Abseil Team87a4c072018-06-25 09:18:19 -0700111 FixedArray(const FixedArray& other)
112 : FixedArray(other.begin(), other.end()) {}
113
Abseil Team6365d172018-01-02 08:53:02 -0800114 FixedArray(FixedArray&& other) noexcept(
115 // clang-format off
116 absl::allocator_is_nothrow<std::allocator<value_type>>::value &&
117 // clang-format on
118 std::is_nothrow_move_constructible<value_type>::value)
Abseil Team87a4c072018-06-25 09:18:19 -0700119 : FixedArray(std::make_move_iterator(other.begin()),
120 std::make_move_iterator(other.end())) {}
Abseil Team6365d172018-01-02 08:53:02 -0800121
mistergc2e75482017-09-19 16:54:40 -0400122 // Creates an array object that can store `n` elements.
123 // Note that trivially constructible elements will be uninitialized.
Abseil Team87a4c072018-06-25 09:18:19 -0700124 explicit FixedArray(size_type n) : rep_(n) {
125 absl::memory_internal::uninitialized_default_construct_n(rep_.begin(),
126 size());
127 }
mistergc2e75482017-09-19 16:54:40 -0400128
129 // Creates an array initialized with `n` copies of `val`.
Abseil Team87a4c072018-06-25 09:18:19 -0700130 FixedArray(size_type n, const value_type& val) : rep_(n) {
131 std::uninitialized_fill_n(data(), size(), val);
132 }
mistergc2e75482017-09-19 16:54:40 -0400133
134 // Creates an array initialized with the elements from the input
135 // range. The array's size will always be `std::distance(first, last)`.
136 // REQUIRES: Iter must be a forward_iterator or better.
137 template <typename Iter, EnableIfForwardIterator<Iter> = 0>
Abseil Team87a4c072018-06-25 09:18:19 -0700138 FixedArray(Iter first, Iter last) : rep_(std::distance(first, last)) {
139 std::uninitialized_copy(first, last, data());
140 }
mistergc2e75482017-09-19 16:54:40 -0400141
Abseil Team8d8dcb02017-09-29 08:44:28 -0700142 // Creates the array from an initializer_list.
mistergc2e75482017-09-19 16:54:40 -0400143 FixedArray(std::initializer_list<T> init_list)
144 : FixedArray(init_list.begin(), init_list.end()) {}
145
Abseil Team87a4c072018-06-25 09:18:19 -0700146 ~FixedArray() noexcept {
147 for (Holder* cur = rep_.begin(); cur != rep_.end(); ++cur) {
148 cur->~Holder();
149 }
150 }
mistergc2e75482017-09-19 16:54:40 -0400151
Abseil Team6365d172018-01-02 08:53:02 -0800152 // Assignments are deleted because they break the invariant that the size of a
153 // `FixedArray` never changes.
154 void operator=(FixedArray&&) = delete;
mistergc2e75482017-09-19 16:54:40 -0400155 void operator=(const FixedArray&) = delete;
156
157 // FixedArray::size()
158 //
159 // Returns the length of the fixed array.
160 size_type size() const { return rep_.size(); }
161
162 // FixedArray::max_size()
163 //
164 // Returns the largest possible value of `std::distance(begin(), end())` for a
165 // `FixedArray<T>`. This is equivalent to the most possible addressable bytes
166 // over the number of bytes taken by T.
167 constexpr size_type max_size() const {
168 return std::numeric_limits<difference_type>::max() / sizeof(value_type);
169 }
170
171 // FixedArray::empty()
172 //
173 // Returns whether or not the fixed array is empty.
174 bool empty() const { return size() == 0; }
175
176 // FixedArray::memsize()
177 //
178 // Returns the memory size of the fixed array in bytes.
179 size_t memsize() const { return size() * sizeof(value_type); }
180
181 // FixedArray::data()
182 //
183 // Returns a const T* pointer to elements of the `FixedArray`. This pointer
184 // can be used to access (but not modify) the contained elements.
185 const_pointer data() const { return AsValue(rep_.begin()); }
186
187 // Overload of FixedArray::data() to return a T* pointer to elements of the
188 // fixed array. This pointer can be used to access and modify the contained
189 // elements.
190 pointer data() { return AsValue(rep_.begin()); }
Abseil Team787891a2018-01-22 13:10:49 -0800191
mistergc2e75482017-09-19 16:54:40 -0400192 // FixedArray::operator[]
193 //
194 // Returns a reference the ith element of the fixed array.
195 // REQUIRES: 0 <= i < size()
196 reference operator[](size_type i) {
197 assert(i < size());
198 return data()[i];
199 }
200
201 // Overload of FixedArray::operator()[] to return a const reference to the
202 // ith element of the fixed array.
203 // REQUIRES: 0 <= i < size()
204 const_reference operator[](size_type i) const {
205 assert(i < size());
206 return data()[i];
207 }
208
209 // FixedArray::at
210 //
211 // Bounds-checked access. Returns a reference to the ith element of the
212 // fiexed array, or throws std::out_of_range
213 reference at(size_type i) {
214 if (ABSL_PREDICT_FALSE(i >= size())) {
215 base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
216 }
217 return data()[i];
218 }
219
220 // Overload of FixedArray::at() to return a const reference to the ith element
221 // of the fixed array.
222 const_reference at(size_type i) const {
Abseil Team5b535402018-04-18 05:56:39 -0700223 if (ABSL_PREDICT_FALSE(i >= size())) {
mistergc2e75482017-09-19 16:54:40 -0400224 base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
225 }
226 return data()[i];
227 }
228
229 // FixedArray::front()
230 //
231 // Returns a reference to the first element of the fixed array.
232 reference front() { return *begin(); }
233
234 // Overload of FixedArray::front() to return a reference to the first element
235 // of a fixed array of const values.
236 const_reference front() const { return *begin(); }
237
238 // FixedArray::back()
239 //
240 // Returns a reference to the last element of the fixed array.
241 reference back() { return *(end() - 1); }
242
243 // Overload of FixedArray::back() to return a reference to the last element
244 // of a fixed array of const values.
245 const_reference back() const { return *(end() - 1); }
246
247 // FixedArray::begin()
248 //
249 // Returns an iterator to the beginning of the fixed array.
250 iterator begin() { return data(); }
251
252 // Overload of FixedArray::begin() to return a const iterator to the
253 // beginning of the fixed array.
254 const_iterator begin() const { return data(); }
255
256 // FixedArray::cbegin()
257 //
258 // Returns a const iterator to the beginning of the fixed array.
259 const_iterator cbegin() const { return begin(); }
260
261 // FixedArray::end()
262 //
263 // Returns an iterator to the end of the fixed array.
264 iterator end() { return data() + size(); }
265
266 // Overload of FixedArray::end() to return a const iterator to the end of the
267 // fixed array.
268 const_iterator end() const { return data() + size(); }
269
270 // FixedArray::cend()
271 //
272 // Returns a const iterator to the end of the fixed array.
273 const_iterator cend() const { return end(); }
274
275 // FixedArray::rbegin()
276 //
277 // Returns a reverse iterator from the end of the fixed array.
278 reverse_iterator rbegin() { return reverse_iterator(end()); }
279
280 // Overload of FixedArray::rbegin() to return a const reverse iterator from
281 // the end of the fixed array.
282 const_reverse_iterator rbegin() const {
283 return const_reverse_iterator(end());
284 }
285
286 // FixedArray::crbegin()
287 //
288 // Returns a const reverse iterator from the end of the fixed array.
289 const_reverse_iterator crbegin() const { return rbegin(); }
290
291 // FixedArray::rend()
292 //
293 // Returns a reverse iterator from the beginning of the fixed array.
294 reverse_iterator rend() { return reverse_iterator(begin()); }
295
296 // Overload of FixedArray::rend() for returning a const reverse iterator
297 // from the beginning of the fixed array.
298 const_reverse_iterator rend() const {
299 return const_reverse_iterator(begin());
300 }
301
302 // FixedArray::crend()
303 //
304 // Returns a reverse iterator from the beginning of the fixed array.
305 const_reverse_iterator crend() const { return rend(); }
306
307 // FixedArray::fill()
308 //
309 // Assigns the given `value` to all elements in the fixed array.
310 void fill(const T& value) { std::fill(begin(), end(), value); }
311
312 // Relational operators. Equality operators are elementwise using
313 // `operator==`, while order operators order FixedArrays lexicographically.
314 friend bool operator==(const FixedArray& lhs, const FixedArray& rhs) {
315 return absl::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
316 }
317
318 friend bool operator!=(const FixedArray& lhs, const FixedArray& rhs) {
319 return !(lhs == rhs);
320 }
321
322 friend bool operator<(const FixedArray& lhs, const FixedArray& rhs) {
323 return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
324 rhs.end());
325 }
326
327 friend bool operator>(const FixedArray& lhs, const FixedArray& rhs) {
328 return rhs < lhs;
329 }
330
331 friend bool operator<=(const FixedArray& lhs, const FixedArray& rhs) {
332 return !(rhs < lhs);
333 }
334
335 friend bool operator>=(const FixedArray& lhs, const FixedArray& rhs) {
336 return !(lhs < rhs);
337 }
338
339 private:
340 // HolderTraits
341 //
342 // Wrapper to hold elements of type T for the case where T is an array type.
343 // If 'T' is an array type, HolderTraits::type is a struct with a 'T v;'.
344 // Otherwise, HolderTraits::type is simply 'T'.
345 //
346 // Maintainer's Note: The simpler solution would be to simply wrap T in a
347 // struct whether it's an array or not: 'struct Holder { T v; };', but
348 // that causes some paranoid diagnostics to misfire about uses of data(),
349 // believing that 'data()' (aka '&rep_.begin().v') is a pointer to a single
350 // element, rather than the packed array that it really is.
351 // e.g.:
352 //
353 // FixedArray<char> buf(1);
354 // sprintf(buf.data(), "foo");
355 //
356 // error: call to int __builtin___sprintf_chk(etc...)
357 // will always overflow destination buffer [-Werror]
358 //
359 class HolderTraits {
360 template <typename U>
361 struct SelectImpl {
362 using type = U;
363 static pointer AsValue(type* p) { return p; }
364 };
365
366 // Partial specialization for elements of array type.
367 template <typename U, size_t N>
368 struct SelectImpl<U[N]> {
369 struct Holder { U v[N]; };
370 using type = Holder;
371 static pointer AsValue(type* p) { return &p->v; }
372 };
373 using Impl = SelectImpl<value_type>;
374
375 public:
376 using type = typename Impl::type;
377
378 static pointer AsValue(type *p) { return Impl::AsValue(p); }
379
380 // TODO(billydonahue): fix the type aliasing violation
381 // this assertion hints at.
382 static_assert(sizeof(type) == sizeof(value_type),
383 "Holder must be same size as value_type");
384 };
385
386 using Holder = typename HolderTraits::type;
387 static pointer AsValue(Holder *p) { return HolderTraits::AsValue(p); }
388
389 // InlineSpace
390 //
391 // Allocate some space, not an array of elements of type T, so that we can
392 // skip calling the T constructors and destructors for space we never use.
393 // How many elements should we store inline?
394 // a. If not specified, use a default of kInlineBytesDefault bytes (This is
395 // currently 256 bytes, which seems small enough to not cause stack overflow
396 // or unnecessary stack pollution, while still allowing stack allocation for
397 // reasonably long character arrays).
398 // b. Never use 0 length arrays (not ISO C++)
399 //
400 template <size_type N, typename = void>
401 class InlineSpace {
402 public:
403 Holder* data() { return reinterpret_cast<Holder*>(space_.data()); }
404 void AnnotateConstruct(size_t n) const { Annotate(n, true); }
405 void AnnotateDestruct(size_t n) const { Annotate(n, false); }
406
407 private:
408#ifndef ADDRESS_SANITIZER
409 void Annotate(size_t, bool) const { }
410#else
411 void Annotate(size_t n, bool creating) const {
412 if (!n) return;
413 const void* bot = &left_redzone_;
414 const void* beg = space_.data();
415 const void* end = space_.data() + n;
416 const void* top = &right_redzone_ + 1;
417 // args: (beg, end, old_mid, new_mid)
418 if (creating) {
419 ANNOTATE_CONTIGUOUS_CONTAINER(beg, top, top, end);
420 ANNOTATE_CONTIGUOUS_CONTAINER(bot, beg, beg, bot);
421 } else {
422 ANNOTATE_CONTIGUOUS_CONTAINER(beg, top, end, top);
423 ANNOTATE_CONTIGUOUS_CONTAINER(bot, beg, bot, beg);
424 }
425 }
426#endif // ADDRESS_SANITIZER
427
428 using Buffer =
429 typename std::aligned_storage<sizeof(Holder), alignof(Holder)>::type;
430
431 ADDRESS_SANITIZER_REDZONE(left_redzone_);
432 std::array<Buffer, N> space_;
433 ADDRESS_SANITIZER_REDZONE(right_redzone_);
434 };
435
436 // specialization when N = 0.
437 template <typename U>
438 class InlineSpace<0, U> {
439 public:
440 Holder* data() { return nullptr; }
441 void AnnotateConstruct(size_t) const {}
442 void AnnotateDestruct(size_t) const {}
443 };
444
445 // Rep
446 //
Abseil Team87a4c072018-06-25 09:18:19 -0700447 // An instance of Rep manages the inline and out-of-line memory for FixedArray
mistergc2e75482017-09-19 16:54:40 -0400448 //
449 class Rep : public InlineSpace<inline_elements> {
450 public:
Abseil Team87a4c072018-06-25 09:18:19 -0700451 explicit Rep(size_type n) : n_(n), p_(MakeHolder(n)) {}
mistergc2e75482017-09-19 16:54:40 -0400452
Abseil Team87a4c072018-06-25 09:18:19 -0700453 ~Rep() noexcept {
mistergc2e75482017-09-19 16:54:40 -0400454 if (IsAllocated(size())) {
Abseil Teamf6eea942018-01-25 10:52:02 -0800455 std::allocator<Holder>().deallocate(p_, n_);
mistergc2e75482017-09-19 16:54:40 -0400456 } else {
457 this->AnnotateDestruct(size());
458 }
459 }
460 Holder* begin() const { return p_; }
461 Holder* end() const { return p_ + n_; }
462 size_type size() const { return n_; }
463
464 private:
465 Holder* MakeHolder(size_type n) {
466 if (IsAllocated(n)) {
Abseil Teamf6eea942018-01-25 10:52:02 -0800467 return std::allocator<Holder>().allocate(n);
mistergc2e75482017-09-19 16:54:40 -0400468 } else {
469 this->AnnotateConstruct(n);
470 return this->data();
471 }
472 }
473
mistergc2e75482017-09-19 16:54:40 -0400474 bool IsAllocated(size_type n) const { return n > inline_elements; }
475
476 const size_type n_;
477 Holder* const p_;
478 };
479
480
481 // Data members
482 Rep rep_;
483};
484
485template <typename T, size_t N>
486constexpr size_t FixedArray<T, N>::inline_elements;
487
488template <typename T, size_t N>
489constexpr size_t FixedArray<T, N>::kInlineBytesDefault;
490
491} // namespace absl
492#endif // ABSL_CONTAINER_FIXED_ARRAY_H_