fixed_array.h 19 KB

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