misterg | c2e7548 | 2017-09-19 16:54:40 -0400 | [diff] [blame] | 1 | // 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 Team | 6365d17 | 2018-01-02 08:53:02 -0800 | [diff] [blame^] | 50 | #include "absl/memory/memory.h" |
misterg | c2e7548 | 2017-09-19 16:54:40 -0400 | [diff] [blame] | 51 | |
| 52 | namespace absl { |
| 53 | |
| 54 | constexpr 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. |
| 79 | template <typename T, size_t inlined = kFixedArrayUseDefault> |
| 80 | class 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 Team | 6365d17 | 2018-01-02 08:53:02 -0800 | [diff] [blame^] | 111 | FixedArray(const FixedArray& other) : rep_(other.begin(), other.end()) {} |
| 112 | FixedArray(FixedArray&& other) noexcept( |
| 113 | // clang-format off |
| 114 | absl::allocator_is_nothrow<std::allocator<value_type>>::value && |
| 115 | // clang-format on |
| 116 | std::is_nothrow_move_constructible<value_type>::value) |
| 117 | : rep_(std::make_move_iterator(other.begin()), |
| 118 | std::make_move_iterator(other.end())) {} |
| 119 | |
misterg | c2e7548 | 2017-09-19 16:54:40 -0400 | [diff] [blame] | 120 | // Creates an array object that can store `n` elements. |
| 121 | // Note that trivially constructible elements will be uninitialized. |
| 122 | explicit FixedArray(size_type n) : rep_(n) {} |
| 123 | |
| 124 | // Creates an array initialized with `n` copies of `val`. |
| 125 | FixedArray(size_type n, const value_type& val) : rep_(n, val) {} |
| 126 | |
| 127 | // Creates an array initialized with the elements from the input |
| 128 | // range. The array's size will always be `std::distance(first, last)`. |
| 129 | // REQUIRES: Iter must be a forward_iterator or better. |
| 130 | template <typename Iter, EnableIfForwardIterator<Iter> = 0> |
| 131 | FixedArray(Iter first, Iter last) : rep_(first, last) {} |
| 132 | |
Abseil Team | 8d8dcb0 | 2017-09-29 08:44:28 -0700 | [diff] [blame] | 133 | // Creates the array from an initializer_list. |
misterg | c2e7548 | 2017-09-19 16:54:40 -0400 | [diff] [blame] | 134 | FixedArray(std::initializer_list<T> init_list) |
| 135 | : FixedArray(init_list.begin(), init_list.end()) {} |
| 136 | |
| 137 | ~FixedArray() {} |
| 138 | |
Abseil Team | 6365d17 | 2018-01-02 08:53:02 -0800 | [diff] [blame^] | 139 | // Assignments are deleted because they break the invariant that the size of a |
| 140 | // `FixedArray` never changes. |
| 141 | void operator=(FixedArray&&) = delete; |
misterg | c2e7548 | 2017-09-19 16:54:40 -0400 | [diff] [blame] | 142 | void operator=(const FixedArray&) = delete; |
| 143 | |
| 144 | // FixedArray::size() |
| 145 | // |
| 146 | // Returns the length of the fixed array. |
| 147 | size_type size() const { return rep_.size(); } |
| 148 | |
| 149 | // FixedArray::max_size() |
| 150 | // |
| 151 | // Returns the largest possible value of `std::distance(begin(), end())` for a |
| 152 | // `FixedArray<T>`. This is equivalent to the most possible addressable bytes |
| 153 | // over the number of bytes taken by T. |
| 154 | constexpr size_type max_size() const { |
| 155 | return std::numeric_limits<difference_type>::max() / sizeof(value_type); |
| 156 | } |
| 157 | |
| 158 | // FixedArray::empty() |
| 159 | // |
| 160 | // Returns whether or not the fixed array is empty. |
| 161 | bool empty() const { return size() == 0; } |
| 162 | |
| 163 | // FixedArray::memsize() |
| 164 | // |
| 165 | // Returns the memory size of the fixed array in bytes. |
| 166 | size_t memsize() const { return size() * sizeof(value_type); } |
| 167 | |
| 168 | // FixedArray::data() |
| 169 | // |
| 170 | // Returns a const T* pointer to elements of the `FixedArray`. This pointer |
| 171 | // can be used to access (but not modify) the contained elements. |
| 172 | const_pointer data() const { return AsValue(rep_.begin()); } |
| 173 | |
| 174 | // Overload of FixedArray::data() to return a T* pointer to elements of the |
| 175 | // fixed array. This pointer can be used to access and modify the contained |
| 176 | // elements. |
| 177 | pointer data() { return AsValue(rep_.begin()); } |
| 178 | // FixedArray::operator[] |
| 179 | // |
| 180 | // Returns a reference the ith element of the fixed array. |
| 181 | // REQUIRES: 0 <= i < size() |
| 182 | reference operator[](size_type i) { |
| 183 | assert(i < size()); |
| 184 | return data()[i]; |
| 185 | } |
| 186 | |
| 187 | // Overload of FixedArray::operator()[] to return a const reference to the |
| 188 | // ith element of the fixed array. |
| 189 | // REQUIRES: 0 <= i < size() |
| 190 | const_reference operator[](size_type i) const { |
| 191 | assert(i < size()); |
| 192 | return data()[i]; |
| 193 | } |
| 194 | |
| 195 | // FixedArray::at |
| 196 | // |
| 197 | // Bounds-checked access. Returns a reference to the ith element of the |
| 198 | // fiexed array, or throws std::out_of_range |
| 199 | reference at(size_type i) { |
| 200 | if (ABSL_PREDICT_FALSE(i >= size())) { |
| 201 | base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check"); |
| 202 | } |
| 203 | return data()[i]; |
| 204 | } |
| 205 | |
| 206 | // Overload of FixedArray::at() to return a const reference to the ith element |
| 207 | // of the fixed array. |
| 208 | const_reference at(size_type i) const { |
| 209 | if (i >= size()) { |
| 210 | base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check"); |
| 211 | } |
| 212 | return data()[i]; |
| 213 | } |
| 214 | |
| 215 | // FixedArray::front() |
| 216 | // |
| 217 | // Returns a reference to the first element of the fixed array. |
| 218 | reference front() { return *begin(); } |
| 219 | |
| 220 | // Overload of FixedArray::front() to return a reference to the first element |
| 221 | // of a fixed array of const values. |
| 222 | const_reference front() const { return *begin(); } |
| 223 | |
| 224 | // FixedArray::back() |
| 225 | // |
| 226 | // Returns a reference to the last element of the fixed array. |
| 227 | reference back() { return *(end() - 1); } |
| 228 | |
| 229 | // Overload of FixedArray::back() to return a reference to the last element |
| 230 | // of a fixed array of const values. |
| 231 | const_reference back() const { return *(end() - 1); } |
| 232 | |
| 233 | // FixedArray::begin() |
| 234 | // |
| 235 | // Returns an iterator to the beginning of the fixed array. |
| 236 | iterator begin() { return data(); } |
| 237 | |
| 238 | // Overload of FixedArray::begin() to return a const iterator to the |
| 239 | // beginning of the fixed array. |
| 240 | const_iterator begin() const { return data(); } |
| 241 | |
| 242 | // FixedArray::cbegin() |
| 243 | // |
| 244 | // Returns a const iterator to the beginning of the fixed array. |
| 245 | const_iterator cbegin() const { return begin(); } |
| 246 | |
| 247 | // FixedArray::end() |
| 248 | // |
| 249 | // Returns an iterator to the end of the fixed array. |
| 250 | iterator end() { return data() + size(); } |
| 251 | |
| 252 | // Overload of FixedArray::end() to return a const iterator to the end of the |
| 253 | // fixed array. |
| 254 | const_iterator end() const { return data() + size(); } |
| 255 | |
| 256 | // FixedArray::cend() |
| 257 | // |
| 258 | // Returns a const iterator to the end of the fixed array. |
| 259 | const_iterator cend() const { return end(); } |
| 260 | |
| 261 | // FixedArray::rbegin() |
| 262 | // |
| 263 | // Returns a reverse iterator from the end of the fixed array. |
| 264 | reverse_iterator rbegin() { return reverse_iterator(end()); } |
| 265 | |
| 266 | // Overload of FixedArray::rbegin() to return a const reverse iterator from |
| 267 | // the end of the fixed array. |
| 268 | const_reverse_iterator rbegin() const { |
| 269 | return const_reverse_iterator(end()); |
| 270 | } |
| 271 | |
| 272 | // FixedArray::crbegin() |
| 273 | // |
| 274 | // Returns a const reverse iterator from the end of the fixed array. |
| 275 | const_reverse_iterator crbegin() const { return rbegin(); } |
| 276 | |
| 277 | // FixedArray::rend() |
| 278 | // |
| 279 | // Returns a reverse iterator from the beginning of the fixed array. |
| 280 | reverse_iterator rend() { return reverse_iterator(begin()); } |
| 281 | |
| 282 | // Overload of FixedArray::rend() for returning a const reverse iterator |
| 283 | // from the beginning of the fixed array. |
| 284 | const_reverse_iterator rend() const { |
| 285 | return const_reverse_iterator(begin()); |
| 286 | } |
| 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 | |
| 293 | // FixedArray::fill() |
| 294 | // |
| 295 | // Assigns the given `value` to all elements in the fixed array. |
| 296 | void fill(const T& value) { std::fill(begin(), end(), value); } |
| 297 | |
| 298 | // Relational operators. Equality operators are elementwise using |
| 299 | // `operator==`, while order operators order FixedArrays lexicographically. |
| 300 | friend bool operator==(const FixedArray& lhs, const FixedArray& rhs) { |
| 301 | return absl::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); |
| 302 | } |
| 303 | |
| 304 | friend bool operator!=(const FixedArray& lhs, const FixedArray& rhs) { |
| 305 | return !(lhs == rhs); |
| 306 | } |
| 307 | |
| 308 | friend bool operator<(const FixedArray& lhs, const FixedArray& rhs) { |
| 309 | return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), |
| 310 | rhs.end()); |
| 311 | } |
| 312 | |
| 313 | friend bool operator>(const FixedArray& lhs, const FixedArray& rhs) { |
| 314 | return rhs < lhs; |
| 315 | } |
| 316 | |
| 317 | friend bool operator<=(const FixedArray& lhs, const FixedArray& rhs) { |
| 318 | return !(rhs < lhs); |
| 319 | } |
| 320 | |
| 321 | friend bool operator>=(const FixedArray& lhs, const FixedArray& rhs) { |
| 322 | return !(lhs < rhs); |
| 323 | } |
| 324 | |
| 325 | private: |
| 326 | // HolderTraits |
| 327 | // |
| 328 | // Wrapper to hold elements of type T for the case where T is an array type. |
| 329 | // If 'T' is an array type, HolderTraits::type is a struct with a 'T v;'. |
| 330 | // Otherwise, HolderTraits::type is simply 'T'. |
| 331 | // |
| 332 | // Maintainer's Note: The simpler solution would be to simply wrap T in a |
| 333 | // struct whether it's an array or not: 'struct Holder { T v; };', but |
| 334 | // that causes some paranoid diagnostics to misfire about uses of data(), |
| 335 | // believing that 'data()' (aka '&rep_.begin().v') is a pointer to a single |
| 336 | // element, rather than the packed array that it really is. |
| 337 | // e.g.: |
| 338 | // |
| 339 | // FixedArray<char> buf(1); |
| 340 | // sprintf(buf.data(), "foo"); |
| 341 | // |
| 342 | // error: call to int __builtin___sprintf_chk(etc...) |
| 343 | // will always overflow destination buffer [-Werror] |
| 344 | // |
| 345 | class HolderTraits { |
| 346 | template <typename U> |
| 347 | struct SelectImpl { |
| 348 | using type = U; |
| 349 | static pointer AsValue(type* p) { return p; } |
| 350 | }; |
| 351 | |
| 352 | // Partial specialization for elements of array type. |
| 353 | template <typename U, size_t N> |
| 354 | struct SelectImpl<U[N]> { |
| 355 | struct Holder { U v[N]; }; |
| 356 | using type = Holder; |
| 357 | static pointer AsValue(type* p) { return &p->v; } |
| 358 | }; |
| 359 | using Impl = SelectImpl<value_type>; |
| 360 | |
| 361 | public: |
| 362 | using type = typename Impl::type; |
| 363 | |
| 364 | static pointer AsValue(type *p) { return Impl::AsValue(p); } |
| 365 | |
| 366 | // TODO(billydonahue): fix the type aliasing violation |
| 367 | // this assertion hints at. |
| 368 | static_assert(sizeof(type) == sizeof(value_type), |
| 369 | "Holder must be same size as value_type"); |
| 370 | }; |
| 371 | |
| 372 | using Holder = typename HolderTraits::type; |
| 373 | static pointer AsValue(Holder *p) { return HolderTraits::AsValue(p); } |
| 374 | |
| 375 | // InlineSpace |
| 376 | // |
| 377 | // Allocate some space, not an array of elements of type T, so that we can |
| 378 | // skip calling the T constructors and destructors for space we never use. |
| 379 | // How many elements should we store inline? |
| 380 | // a. If not specified, use a default of kInlineBytesDefault bytes (This is |
| 381 | // currently 256 bytes, which seems small enough to not cause stack overflow |
| 382 | // or unnecessary stack pollution, while still allowing stack allocation for |
| 383 | // reasonably long character arrays). |
| 384 | // b. Never use 0 length arrays (not ISO C++) |
| 385 | // |
| 386 | template <size_type N, typename = void> |
| 387 | class InlineSpace { |
| 388 | public: |
| 389 | Holder* data() { return reinterpret_cast<Holder*>(space_.data()); } |
| 390 | void AnnotateConstruct(size_t n) const { Annotate(n, true); } |
| 391 | void AnnotateDestruct(size_t n) const { Annotate(n, false); } |
| 392 | |
| 393 | private: |
| 394 | #ifndef ADDRESS_SANITIZER |
| 395 | void Annotate(size_t, bool) const { } |
| 396 | #else |
| 397 | void Annotate(size_t n, bool creating) const { |
| 398 | if (!n) return; |
| 399 | const void* bot = &left_redzone_; |
| 400 | const void* beg = space_.data(); |
| 401 | const void* end = space_.data() + n; |
| 402 | const void* top = &right_redzone_ + 1; |
| 403 | // args: (beg, end, old_mid, new_mid) |
| 404 | if (creating) { |
| 405 | ANNOTATE_CONTIGUOUS_CONTAINER(beg, top, top, end); |
| 406 | ANNOTATE_CONTIGUOUS_CONTAINER(bot, beg, beg, bot); |
| 407 | } else { |
| 408 | ANNOTATE_CONTIGUOUS_CONTAINER(beg, top, end, top); |
| 409 | ANNOTATE_CONTIGUOUS_CONTAINER(bot, beg, bot, beg); |
| 410 | } |
| 411 | } |
| 412 | #endif // ADDRESS_SANITIZER |
| 413 | |
| 414 | using Buffer = |
| 415 | typename std::aligned_storage<sizeof(Holder), alignof(Holder)>::type; |
| 416 | |
| 417 | ADDRESS_SANITIZER_REDZONE(left_redzone_); |
| 418 | std::array<Buffer, N> space_; |
| 419 | ADDRESS_SANITIZER_REDZONE(right_redzone_); |
| 420 | }; |
| 421 | |
| 422 | // specialization when N = 0. |
| 423 | template <typename U> |
| 424 | class InlineSpace<0, U> { |
| 425 | public: |
| 426 | Holder* data() { return nullptr; } |
| 427 | void AnnotateConstruct(size_t) const {} |
| 428 | void AnnotateDestruct(size_t) const {} |
| 429 | }; |
| 430 | |
| 431 | // Rep |
| 432 | // |
| 433 | // A const Rep object holds FixedArray's size and data pointer. |
| 434 | // |
| 435 | class Rep : public InlineSpace<inline_elements> { |
| 436 | public: |
| 437 | Rep(size_type n, const value_type& val) : n_(n), p_(MakeHolder(n)) { |
| 438 | std::uninitialized_fill_n(p_, n, val); |
| 439 | } |
| 440 | |
| 441 | explicit Rep(size_type n) : n_(n), p_(MakeHolder(n)) { |
| 442 | // Loop optimizes to nothing for trivially constructible T. |
| 443 | for (Holder* p = p_; p != p_ + n; ++p) |
| 444 | // Note: no parens: default init only. |
| 445 | // Also note '::' to avoid Holder class placement new operator. |
| 446 | ::new (static_cast<void*>(p)) Holder; |
| 447 | } |
| 448 | |
| 449 | template <typename Iter> |
| 450 | Rep(Iter first, Iter last) |
| 451 | : n_(std::distance(first, last)), p_(MakeHolder(n_)) { |
| 452 | std::uninitialized_copy(first, last, AsValue(p_)); |
| 453 | } |
| 454 | |
| 455 | ~Rep() { |
| 456 | // Destruction must be in reverse order. |
| 457 | // Loop optimizes to nothing for trivially destructible T. |
| 458 | for (Holder* p = end(); p != begin();) (--p)->~Holder(); |
| 459 | if (IsAllocated(size())) { |
| 460 | ::operator delete[](begin()); |
| 461 | } else { |
| 462 | this->AnnotateDestruct(size()); |
| 463 | } |
| 464 | } |
| 465 | Holder* begin() const { return p_; } |
| 466 | Holder* end() const { return p_ + n_; } |
| 467 | size_type size() const { return n_; } |
| 468 | |
| 469 | private: |
| 470 | Holder* MakeHolder(size_type n) { |
| 471 | if (IsAllocated(n)) { |
| 472 | return Allocate(n); |
| 473 | } else { |
| 474 | this->AnnotateConstruct(n); |
| 475 | return this->data(); |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | Holder* Allocate(size_type n) { |
| 480 | return static_cast<Holder*>(::operator new[](n * sizeof(Holder))); |
| 481 | } |
| 482 | |
| 483 | bool IsAllocated(size_type n) const { return n > inline_elements; } |
| 484 | |
| 485 | const size_type n_; |
| 486 | Holder* const p_; |
| 487 | }; |
| 488 | |
| 489 | |
| 490 | // Data members |
| 491 | Rep rep_; |
| 492 | }; |
| 493 | |
| 494 | template <typename T, size_t N> |
| 495 | constexpr size_t FixedArray<T, N>::inline_elements; |
| 496 | |
| 497 | template <typename T, size_t N> |
| 498 | constexpr size_t FixedArray<T, N>::kInlineBytesDefault; |
| 499 | |
| 500 | } // namespace absl |
| 501 | #endif // ABSL_CONTAINER_FIXED_ARRAY_H_ |