fixed_array.h 19 KB

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