Coverage Report

Created: 2025-07-11 06:37

/src/abseil-cpp/absl/container/fixed_array.h
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2018 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
//      https://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 <cassert>
35
#include <cstddef>
36
#include <initializer_list>
37
#include <iterator>
38
#include <limits>
39
#include <memory>
40
#include <new>
41
#include <type_traits>
42
43
#include "absl/algorithm/algorithm.h"
44
#include "absl/base/attributes.h"
45
#include "absl/base/config.h"
46
#include "absl/base/dynamic_annotations.h"
47
#include "absl/base/internal/iterator_traits.h"
48
#include "absl/base/internal/throw_delegate.h"
49
#include "absl/base/macros.h"
50
#include "absl/base/optimization.h"
51
#include "absl/base/port.h"
52
#include "absl/container/internal/compressed_tuple.h"
53
#include "absl/hash/internal/weakly_mixed_integer.h"
54
#include "absl/memory/memory.h"
55
56
namespace absl {
57
ABSL_NAMESPACE_BEGIN
58
59
constexpr static auto kFixedArrayUseDefault = static_cast<size_t>(-1);
60
61
// -----------------------------------------------------------------------------
62
// FixedArray
63
// -----------------------------------------------------------------------------
64
//
65
// A `FixedArray` provides a run-time fixed-size array, allocating a small array
66
// inline for efficiency.
67
//
68
// Most users should not specify the `N` template parameter and let `FixedArray`
69
// automatically determine the number of elements to store inline based on
70
// `sizeof(T)`. If `N` is specified, the `FixedArray` implementation will use
71
// inline storage for arrays with a length <= `N`.
72
//
73
// Note that a `FixedArray` constructed with a `size_type` argument will
74
// default-initialize its values by leaving trivially constructible types
75
// uninitialized (e.g. int, int[4], double), and others default-constructed.
76
// This matches the behavior of c-style arrays and `std::array`, but not
77
// `std::vector`.
78
template <typename T, size_t N = kFixedArrayUseDefault,
79
          typename A = std::allocator<T>>
80
class ABSL_ATTRIBUTE_WARN_UNUSED FixedArray {
81
  static_assert(!std::is_array<T>::value || std::extent<T>::value > 0,
82
                "Arrays with unknown bounds cannot be used with FixedArray.");
83
84
  static constexpr size_t kInlineBytesDefault = 256;
85
86
  using AllocatorTraits = std::allocator_traits<A>;
87
  // std::iterator_traits isn't guaranteed to be SFINAE-friendly until C++17,
88
  // but this seems to be mostly pedantic.
89
  template <typename Iterator>
90
  using EnableIfForwardIterator = std::enable_if_t<
91
      base_internal::IsAtLeastForwardIterator<Iterator>::value>;
92
  static constexpr bool NoexceptCopyable() {
93
    return std::is_nothrow_copy_constructible<StorageElement>::value &&
94
           absl::allocator_is_nothrow<allocator_type>::value;
95
  }
96
  static constexpr bool NoexceptMovable() {
97
    return std::is_nothrow_move_constructible<StorageElement>::value &&
98
           absl::allocator_is_nothrow<allocator_type>::value;
99
  }
100
0
  static constexpr bool DefaultConstructorIsNonTrivial() {
101
0
    return !absl::is_trivially_default_constructible<StorageElement>::value;
102
0
  }
103
104
 public:
105
  using allocator_type = typename AllocatorTraits::allocator_type;
106
  using value_type = typename AllocatorTraits::value_type;
107
  using pointer = typename AllocatorTraits::pointer;
108
  using const_pointer = typename AllocatorTraits::const_pointer;
109
  using reference = value_type&;
110
  using const_reference = const value_type&;
111
  using size_type = typename AllocatorTraits::size_type;
112
  using difference_type = typename AllocatorTraits::difference_type;
113
  using iterator = pointer;
114
  using const_iterator = const_pointer;
115
  using reverse_iterator = std::reverse_iterator<iterator>;
116
  using const_reverse_iterator = std::reverse_iterator<const_iterator>;
117
118
  static constexpr size_type inline_elements =
119
      (N == kFixedArrayUseDefault ? kInlineBytesDefault / sizeof(value_type)
120
                                  : static_cast<size_type>(N));
121
122
  FixedArray(const FixedArray& other) noexcept(NoexceptCopyable())
123
      : FixedArray(other,
124
                   AllocatorTraits::select_on_container_copy_construction(
125
                       other.storage_.alloc())) {}
126
127
  FixedArray(const FixedArray& other,
128
             const allocator_type& a) noexcept(NoexceptCopyable())
129
      : FixedArray(other.begin(), other.end(), a) {}
130
131
  FixedArray(FixedArray&& other) noexcept(NoexceptMovable())
132
      : FixedArray(std::move(other), other.storage_.alloc()) {}
133
134
  FixedArray(FixedArray&& other,
135
             const allocator_type& a) noexcept(NoexceptMovable())
136
      : FixedArray(std::make_move_iterator(other.begin()),
137
                   std::make_move_iterator(other.end()), a) {}
138
139
  // Creates an array object that can store `n` elements.
140
  // Note that trivially constructible elements will be uninitialized.
141
  explicit FixedArray(size_type n, const allocator_type& a = allocator_type())
142
0
      : storage_(n, a) {
143
0
    if (DefaultConstructorIsNonTrivial()) {
144
0
      memory_internal::ConstructRange(storage_.alloc(), storage_.begin(),
145
0
                                      storage_.end());
146
0
    }
147
0
  }
148
149
  // Creates an array initialized with `n` copies of `val`.
150
  FixedArray(size_type n, const value_type& val,
151
             const allocator_type& a = allocator_type())
152
      : storage_(n, a) {
153
    memory_internal::ConstructRange(storage_.alloc(), storage_.begin(),
154
                                    storage_.end(), val);
155
  }
156
157
  // Creates an array initialized with the size and contents of `init_list`.
158
  FixedArray(std::initializer_list<value_type> init_list,
159
             const allocator_type& a = allocator_type())
160
      : FixedArray(init_list.begin(), init_list.end(), a) {}
161
162
  // Creates an array initialized with the elements from the input
163
  // range. The array's size will always be `std::distance(first, last)`.
164
  // REQUIRES: Iterator must be a forward_iterator or better.
165
  template <typename Iterator, EnableIfForwardIterator<Iterator>* = nullptr>
166
  FixedArray(Iterator first, Iterator last,
167
             const allocator_type& a = allocator_type())
168
      : storage_(std::distance(first, last), a) {
169
    memory_internal::CopyRange(storage_.alloc(), storage_.begin(), first, last);
170
  }
171
172
0
  ~FixedArray() noexcept {
173
0
    for (auto* cur = storage_.begin(); cur != storage_.end(); ++cur) {
174
0
      AllocatorTraits::destroy(storage_.alloc(), cur);
175
0
    }
176
0
  }
177
178
  // Assignments are deleted because they break the invariant that the size of a
179
  // `FixedArray` never changes.
180
  void operator=(FixedArray&&) = delete;
181
  void operator=(const FixedArray&) = delete;
182
183
  // FixedArray::size()
184
  //
185
  // Returns the length of the fixed array.
186
0
  size_type size() const { return storage_.size(); }
187
188
  // FixedArray::max_size()
189
  //
190
  // Returns the largest possible value of `std::distance(begin(), end())` for a
191
  // `FixedArray<T>`. This is equivalent to the most possible addressable bytes
192
  // over the number of bytes taken by T.
193
  constexpr size_type max_size() const {
194
    return (std::numeric_limits<difference_type>::max)() / sizeof(value_type);
195
  }
196
197
  // FixedArray::empty()
198
  //
199
  // Returns whether or not the fixed array is empty.
200
  bool empty() const { return size() == 0; }
201
202
  // FixedArray::memsize()
203
  //
204
  // Returns the memory size of the fixed array in bytes.
205
  size_t memsize() const { return size() * sizeof(value_type); }
206
207
  // FixedArray::data()
208
  //
209
  // Returns a const T* pointer to elements of the `FixedArray`. This pointer
210
  // can be used to access (but not modify) the contained elements.
211
  const_pointer data() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
212
    return AsValueType(storage_.begin());
213
  }
214
215
  // Overload of FixedArray::data() to return a T* pointer to elements of the
216
  // fixed array. This pointer can be used to access and modify the contained
217
  // elements.
218
0
  pointer data() ABSL_ATTRIBUTE_LIFETIME_BOUND {
219
0
    return AsValueType(storage_.begin());
220
0
  }
221
222
  // FixedArray::operator[]
223
  //
224
  // Returns a reference the ith element of the fixed array.
225
  // REQUIRES: 0 <= i < size()
226
0
  reference operator[](size_type i) ABSL_ATTRIBUTE_LIFETIME_BOUND {
227
0
    ABSL_HARDENING_ASSERT(i < size());
228
0
    return data()[i];
229
0
  }
230
231
  // Overload of FixedArray::operator()[] to return a const reference to the
232
  // ith element of the fixed array.
233
  // REQUIRES: 0 <= i < size()
234
  const_reference operator[](size_type i) const ABSL_ATTRIBUTE_LIFETIME_BOUND {
235
    ABSL_HARDENING_ASSERT(i < size());
236
    return data()[i];
237
  }
238
239
  // FixedArray::at
240
  //
241
  // Bounds-checked access.  Returns a reference to the ith element of the fixed
242
  // array, or throws std::out_of_range
243
  reference at(size_type i) ABSL_ATTRIBUTE_LIFETIME_BOUND {
244
    if (ABSL_PREDICT_FALSE(i >= size())) {
245
      base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
246
    }
247
    return data()[i];
248
  }
249
250
  // Overload of FixedArray::at() to return a const reference to the ith element
251
  // of the fixed array.
252
  const_reference at(size_type i) const ABSL_ATTRIBUTE_LIFETIME_BOUND {
253
    if (ABSL_PREDICT_FALSE(i >= size())) {
254
      base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
255
    }
256
    return data()[i];
257
  }
258
259
  // FixedArray::front()
260
  //
261
  // Returns a reference to the first element of the fixed array.
262
  reference front() ABSL_ATTRIBUTE_LIFETIME_BOUND {
263
    ABSL_HARDENING_ASSERT(!empty());
264
    return data()[0];
265
  }
266
267
  // Overload of FixedArray::front() to return a reference to the first element
268
  // of a fixed array of const values.
269
  const_reference front() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
270
    ABSL_HARDENING_ASSERT(!empty());
271
    return data()[0];
272
  }
273
274
  // FixedArray::back()
275
  //
276
  // Returns a reference to the last element of the fixed array.
277
  reference back() ABSL_ATTRIBUTE_LIFETIME_BOUND {
278
    ABSL_HARDENING_ASSERT(!empty());
279
    return data()[size() - 1];
280
  }
281
282
  // Overload of FixedArray::back() to return a reference to the last element
283
  // of a fixed array of const values.
284
  const_reference back() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
285
    ABSL_HARDENING_ASSERT(!empty());
286
    return data()[size() - 1];
287
  }
288
289
  // FixedArray::begin()
290
  //
291
  // Returns an iterator to the beginning of the fixed array.
292
  iterator begin() ABSL_ATTRIBUTE_LIFETIME_BOUND { return data(); }
293
294
  // Overload of FixedArray::begin() to return a const iterator to the
295
  // beginning of the fixed array.
296
  const_iterator begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return data(); }
297
298
  // FixedArray::cbegin()
299
  //
300
  // Returns a const iterator to the beginning of the fixed array.
301
  const_iterator cbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
302
    return begin();
303
  }
304
305
  // FixedArray::end()
306
  //
307
  // Returns an iterator to the end of the fixed array.
308
  iterator end() ABSL_ATTRIBUTE_LIFETIME_BOUND { return data() + size(); }
309
310
  // Overload of FixedArray::end() to return a const iterator to the end of the
311
  // fixed array.
312
  const_iterator end() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
313
    return data() + size();
314
  }
315
316
  // FixedArray::cend()
317
  //
318
  // Returns a const iterator to the end of the fixed array.
319
  const_iterator cend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return end(); }
320
321
  // FixedArray::rbegin()
322
  //
323
  // Returns a reverse iterator from the end of the fixed array.
324
  reverse_iterator rbegin() ABSL_ATTRIBUTE_LIFETIME_BOUND {
325
    return reverse_iterator(end());
326
  }
327
328
  // Overload of FixedArray::rbegin() to return a const reverse iterator from
329
  // the end of the fixed array.
330
  const_reverse_iterator rbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
331
    return const_reverse_iterator(end());
332
  }
333
334
  // FixedArray::crbegin()
335
  //
336
  // Returns a const reverse iterator from the end of the fixed array.
337
  const_reverse_iterator crbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
338
    return rbegin();
339
  }
340
341
  // FixedArray::rend()
342
  //
343
  // Returns a reverse iterator from the beginning of the fixed array.
344
  reverse_iterator rend() ABSL_ATTRIBUTE_LIFETIME_BOUND {
345
    return reverse_iterator(begin());
346
  }
347
348
  // Overload of FixedArray::rend() for returning a const reverse iterator
349
  // from the beginning of the fixed array.
350
  const_reverse_iterator rend() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
351
    return const_reverse_iterator(begin());
352
  }
353
354
  // FixedArray::crend()
355
  //
356
  // Returns a reverse iterator from the beginning of the fixed array.
357
  const_reverse_iterator crend() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
358
    return rend();
359
  }
360
361
  // FixedArray::fill()
362
  //
363
  // Assigns the given `value` to all elements in the fixed array.
364
  void fill(const value_type& val) { std::fill(begin(), end(), val); }
365
366
  // Relational operators. Equality operators are elementwise using
367
  // `operator==`, while order operators order FixedArrays lexicographically.
368
  friend bool operator==(const FixedArray& lhs, const FixedArray& rhs) {
369
    return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
370
  }
371
372
  friend bool operator!=(const FixedArray& lhs, const FixedArray& rhs) {
373
    return !(lhs == rhs);
374
  }
375
376
  friend bool operator<(const FixedArray& lhs, const FixedArray& rhs) {
377
    return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
378
                                        rhs.end());
379
  }
380
381
  friend bool operator>(const FixedArray& lhs, const FixedArray& rhs) {
382
    return rhs < lhs;
383
  }
384
385
  friend bool operator<=(const FixedArray& lhs, const FixedArray& rhs) {
386
    return !(rhs < lhs);
387
  }
388
389
  friend bool operator>=(const FixedArray& lhs, const FixedArray& rhs) {
390
    return !(lhs < rhs);
391
  }
392
393
  template <typename H>
394
  friend H AbslHashValue(H h, const FixedArray& v) {
395
    return H::combine_contiguous(std::move(h), v.data(), v.size());
396
  }
397
398
 private:
399
  // StorageElement
400
  //
401
  // For FixedArrays with a C-style-array value_type, StorageElement is a POD
402
  // wrapper struct called StorageElementWrapper that holds the value_type
403
  // instance inside. This is needed for construction and destruction of the
404
  // entire array regardless of how many dimensions it has. For all other cases,
405
  // StorageElement is just an alias of value_type.
406
  //
407
  // Maintainer's Note: The simpler solution would be to simply wrap value_type
408
  // in a struct whether it's an array or not. That causes some paranoid
409
  // diagnostics to misfire, believing that 'data()' returns a pointer to a
410
  // single element, rather than the packed array that it really is.
411
  // e.g.:
412
  //
413
  //     FixedArray<char> buf(1);
414
  //     sprintf(buf.data(), "foo");
415
  //
416
  //     error: call to int __builtin___sprintf_chk(etc...)
417
  //     will always overflow destination buffer [-Werror]
418
  //
419
  template <typename OuterT, typename InnerT = absl::remove_extent_t<OuterT>,
420
            size_t InnerN = std::extent<OuterT>::value>
421
  struct StorageElementWrapper {
422
    InnerT array[InnerN];
423
  };
424
425
  using StorageElement =
426
      absl::conditional_t<std::is_array<value_type>::value,
427
                          StorageElementWrapper<value_type>, value_type>;
428
429
0
  static pointer AsValueType(pointer ptr) { return ptr; }
430
  static pointer AsValueType(StorageElementWrapper<value_type>* ptr) {
431
    return std::addressof(ptr->array);
432
  }
433
434
  static_assert(sizeof(StorageElement) == sizeof(value_type), "");
435
  static_assert(alignof(StorageElement) == alignof(value_type), "");
436
437
  class NonEmptyInlinedStorage {
438
   public:
439
0
    StorageElement* data() { return reinterpret_cast<StorageElement*>(buff_); }
440
    void AnnotateConstruct(size_type n);
441
    void AnnotateDestruct(size_type n);
442
443
#ifdef ABSL_HAVE_ADDRESS_SANITIZER
444
    void* RedzoneBegin() { return &redzone_begin_; }
445
    void* RedzoneEnd() { return &redzone_end_ + 1; }
446
#endif  // ABSL_HAVE_ADDRESS_SANITIZER
447
448
   private:
449
    ABSL_ADDRESS_SANITIZER_REDZONE(redzone_begin_);
450
    alignas(StorageElement) unsigned char buff_[sizeof(
451
        StorageElement[inline_elements])];
452
    ABSL_ADDRESS_SANITIZER_REDZONE(redzone_end_);
453
  };
454
455
  class EmptyInlinedStorage {
456
   public:
457
    StorageElement* data() { return nullptr; }
458
    void AnnotateConstruct(size_type) {}
459
    void AnnotateDestruct(size_type) {}
460
  };
461
462
  using InlinedStorage =
463
      absl::conditional_t<inline_elements == 0, EmptyInlinedStorage,
464
                          NonEmptyInlinedStorage>;
465
466
  // Storage
467
  //
468
  // An instance of Storage manages the inline and out-of-line memory for
469
  // instances of FixedArray. This guarantees that even when construction of
470
  // individual elements fails in the FixedArray constructor body, the
471
  // destructor for Storage will still be called and out-of-line memory will be
472
  // properly deallocated.
473
  //
474
  class Storage : public InlinedStorage {
475
   public:
476
    Storage(size_type n, const allocator_type& a)
477
0
        : size_alloc_(n, a), data_(InitializeData()) {}
478
479
0
    ~Storage() noexcept {
480
0
      if (UsingInlinedStorage(size())) {
481
0
        InlinedStorage::AnnotateDestruct(size());
482
0
      } else {
483
0
        AllocatorTraits::deallocate(alloc(), AsValueType(begin()), size());
484
0
      }
485
0
    }
486
487
0
    size_type size() const { return size_alloc_.template get<0>(); }
488
0
    StorageElement* begin() const { return data_; }
489
0
    StorageElement* end() const { return begin() + size(); }
490
0
    allocator_type& alloc() { return size_alloc_.template get<1>(); }
491
    const allocator_type& alloc() const {
492
      return size_alloc_.template get<1>();
493
    }
494
495
   private:
496
0
    static bool UsingInlinedStorage(size_type n) {
497
0
      return n <= inline_elements;
498
0
    }
499
500
#ifdef ABSL_HAVE_ADDRESS_SANITIZER
501
    ABSL_ATTRIBUTE_NOINLINE
502
#endif  // ABSL_HAVE_ADDRESS_SANITIZER
503
0
    StorageElement* InitializeData() {
504
0
      if (UsingInlinedStorage(size())) {
505
0
        InlinedStorage::AnnotateConstruct(size());
506
0
        return InlinedStorage::data();
507
0
      } else {
508
0
        return reinterpret_cast<StorageElement*>(
509
0
            AllocatorTraits::allocate(alloc(), size()));
510
0
      }
511
0
    }
512
513
    // `CompressedTuple` takes advantage of EBCO for stateless `allocator_type`s
514
    container_internal::CompressedTuple<size_type, allocator_type> size_alloc_;
515
    StorageElement* data_;
516
  };
517
518
  Storage storage_;
519
};
520
521
template <typename T, size_t N, typename A>
522
void FixedArray<T, N, A>::NonEmptyInlinedStorage::AnnotateConstruct(
523
0
    typename FixedArray<T, N, A>::size_type n) {
524
#ifdef ABSL_HAVE_ADDRESS_SANITIZER
525
  if (!n) return;
526
  ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), RedzoneEnd(),
527
                                     data() + n);
528
  ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), data(),
529
                                     RedzoneBegin());
530
#endif  // ABSL_HAVE_ADDRESS_SANITIZER
531
0
  static_cast<void>(n);  // Mark used when not in asan mode
532
0
}
533
534
template <typename T, size_t N, typename A>
535
void FixedArray<T, N, A>::NonEmptyInlinedStorage::AnnotateDestruct(
536
0
    typename FixedArray<T, N, A>::size_type n) {
537
#ifdef ABSL_HAVE_ADDRESS_SANITIZER
538
  if (!n) return;
539
  ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), data() + n,
540
                                     RedzoneEnd());
541
  ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), RedzoneBegin(),
542
                                     data());
543
#endif  // ABSL_HAVE_ADDRESS_SANITIZER
544
0
  static_cast<void>(n);  // Mark used when not in asan mode
545
0
}
546
ABSL_NAMESPACE_END
547
}  // namespace absl
548
549
#endif  // ABSL_CONTAINER_FIXED_ARRAY_H_