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