| 6 | #define BASE_CONTAINERS_SPAN_H_ |
| 7 |
| 8 | #include <stddef.h> |
| 9 |
| 10 | #include <algorithm> |
| 11 | #include <array> |
| 12 | #include <iterator> |
| 13 | #include <limits> |
| 14 | #include <type_traits> |
| 15 | #include <utility> |
| 16 |
| 17 | #include "base/containers/checked_iterators.h" |
| 18 | #include "base/logging.h" |
| 19 | #include "base/macros.h" |
| 20 | #include "base/stl_util.h" |
| 21 | #include "base/template_util.h" |
| 22 |
| 23 | namespace base { |
| 24 |
| 25 | // [views.constants] |
| 26 | constexpr size_t dynamic_extent = std::numeric_limits<size_t>::max(); |
| 27 |
| 28 | template <typename T, size_t Extent = dynamic_extent> |
| 29 | class span; |
| 30 |
| 31 | namespace internal { |
| 32 |
| 33 | template <size_t I> |
| 34 | using size_constant = std::integral_constant<size_t, I>; |
| 35 |
| 36 | template <typename T> |
| 37 | struct ExtentImpl : size_constant<dynamic_extent> {}; |
| 38 |
| 39 | template <typename T, size_t N> |
| 40 | struct ExtentImpl<T[N]> : size_constant<N> {}; |
| 41 |
| 42 | template <typename T, size_t N> |
| 43 | struct ExtentImpl<std::array<T, N>> : size_constant<N> {}; |
| 44 |
| 45 | template <typename T, size_t N> |
| 46 | struct ExtentImpl<base::span<T, N>> : size_constant<N> {}; |
| 47 |
| 48 | template <typename T> |
| 49 | using Extent = ExtentImpl<std::remove_cv_t<std::remove_reference_t<T>>>; |
| 50 |
| 51 | template <typename T> |
| 52 | struct IsSpanImpl : std::false_type {}; |
| 53 |
| 54 | template <typename T, size_t Extent> |
| 55 | struct IsSpanImpl<span<T, Extent>> : std::true_type {}; |
| 56 |
| 57 | template <typename T> |
| 58 | using IsNotSpan = negation<IsSpanImpl<std::decay_t<T>>>; |
| 59 |
| 60 | template <typename T> |
| 61 | struct IsStdArrayImpl : std::false_type {}; |
| 62 |
| 63 | template <typename T, size_t N> |
| 64 | struct IsStdArrayImpl<std::array<T, N>> : std::true_type {}; |
| 65 |
| 66 | template <typename T> |
| 67 | using IsNotStdArray = negation<IsStdArrayImpl<std::decay_t<T>>>; |
| 68 |
| 69 | template <typename T> |
| 70 | using IsNotCArray = negation<std::is_array<std::remove_reference_t<T>>>; |
| 71 |
| 72 | template <typename From, typename To> |
| 73 | using IsLegalDataConversion = std::is_convertible<From (*)[], To (*)[]>; |
| 74 |
| 75 | template <typename Container, typename T> |
| 76 | using ContainerHasConvertibleData = IsLegalDataConversion< |
| 77 | std::remove_pointer_t<decltype(base::data(std::declval<Container>()))>, |
| 78 | T>; |
| 79 |
| 80 | template <typename Container> |
| 81 | using ContainerHasIntegralSize = |
| 82 | std::is_integral<decltype(base::size(std::declval<Container>()))>; |
| 83 |
| 84 | template <typename From, size_t FromExtent, typename To, size_t ToExtent> |
| 85 | using EnableIfLegalSpanConversion = |
| 86 | std::enable_if_t<(ToExtent == dynamic_extent || ToExtent == FromExtent) && |
| 87 | IsLegalDataConversion<From, To>::value>; |
| 88 |
| 89 | // SFINAE check if Array can be converted to a span<T>. |
| 90 | template <typename Array, typename T, size_t Extent> |
| 91 | using EnableIfSpanCompatibleArray = |
| 92 | std::enable_if_t<(Extent == dynamic_extent || |
| 93 | Extent == internal::Extent<Array>::value) && |
| 94 | ContainerHasConvertibleData<Array, T>::value>; |
| 95 |
| 96 | // SFINAE check if Container can be converted to a span<T>. |
| 97 | template <typename Container, typename T> |
| 98 | using IsSpanCompatibleContainer = |
| 99 | conjunction<IsNotSpan<Container>, |
| 100 | IsNotStdArray<Container>, |
| 101 | IsNotCArray<Container>, |
| 102 | ContainerHasConvertibleData<Container, T>, |
| 103 | ContainerHasIntegralSize<Container>>; |
| 104 |
| 105 | template <typename Container, typename T> |
| 106 | using EnableIfSpanCompatibleContainer = |
| 107 | std::enable_if_t<IsSpanCompatibleContainer<Container, T>::value>; |
| 108 |
| 109 | template <typename Container, typename T, size_t Extent> |
| 110 | using EnableIfSpanCompatibleContainerAndSpanIsDynamic = |
| 111 | std::enable_if_t<IsSpanCompatibleContainer<Container, T>::value && |
| 112 | Extent == dynamic_extent>; |
| 113 |
| 114 | // A helper template for storing the size of a span. Spans with static extents |
| 115 | // don't require additional storage, since the extent itself is specified in the |
| 116 | // template parameter. |
| 117 | template <size_t Extent> |
| 118 | class ExtentStorage { |
| 119 | public: |
| 120 | constexpr explicit ExtentStorage(size_t size) noexcept {} |
| 121 | constexpr size_t size() const noexcept { return Extent; } |
| 122 | }; |
| 123 |
| 124 | // Specialization of ExtentStorage for dynamic extents, which do require |
| 125 | // explicit storage for the size. |
| 126 | template <> |
| 127 | struct ExtentStorage<dynamic_extent> { |
| 128 | constexpr explicit ExtentStorage(size_t size) noexcept : size_(size) {} |
| 129 | constexpr size_t size() const noexcept { return size_; } |
| 130 |
| 131 | private: |
| 132 | size_t size_; |
| 133 | }; |
| 134 |
| 135 | } // namespace internal |
| 136 |
| 137 | // A span is a value type that represents an array of elements of type T. Since |
| 138 | // it only consists of a pointer to memory with an associated size, it is very |
| 139 | // light-weight. It is cheap to construct, copy, move and use spans, so that |
| 140 | // users are encouraged to use it as a pass-by-value parameter. A span does not |
| 141 | // own the underlying memory, so care must be taken to ensure that a span does |
| 142 | // not outlive the backing store. |
| 143 | // |
| 144 | // span is somewhat analogous to StringPiece, but with arbitrary element types, |
| 145 | // allowing mutation if T is non-const. |
| 146 | // |
| 147 | // span is implicitly convertible from C++ arrays, as well as most [1] |
| 148 | // container-like types that provide a data() and size() method (such as |
| 149 | // std::vector<T>). A mutable span<T> can also be implicitly converted to an |
| 150 | // immutable span<const T>. |
| 151 | // |
| 152 | // Consider using a span for functions that take a data pointer and size |
| 153 | // parameter: it allows the function to still act on an array-like type, while |
| 154 | // allowing the caller code to be a bit more concise. |
| 155 | // |
| 156 | // For read-only data access pass a span<const T>: the caller can supply either |
| 157 | // a span<const T> or a span<T>, while the callee will have a read-only view. |
| 158 | // For read-write access a mutable span<T> is required. |
| 159 | // |
| 160 | // Without span: |
| 161 | // Read-Only: |
| 162 | // // std::string HexEncode(const uint8_t* data, size_t size); |
| 163 | // std::vector<uint8_t> data_buffer = GenerateData(); |
| 164 | // std::string r = HexEncode(data_buffer.data(), data_buffer.size()); |
| 165 | // |
| 166 | // Mutable: |
| 167 | // // ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, Args...); |
| 168 | // char str_buffer[100]; |
| 169 | // SafeSNPrintf(str_buffer, sizeof(str_buffer), "Pi ~= %lf", 3.14); |
| 170 | // |
| 171 | // With span: |
| 172 | // Read-Only: |
| 173 | // // std::string HexEncode(base::span<const uint8_t> data); |
| 174 | // std::vector<uint8_t> data_buffer = GenerateData(); |
| 175 | // std::string r = HexEncode(data_buffer); |
| 176 | // |
| 177 | // Mutable: |
| 178 | // // ssize_t SafeSNPrintf(base::span<char>, const char* fmt, Args...); |
| 179 | // char str_buffer[100]; |
| 180 | // SafeSNPrintf(str_buffer, "Pi ~= %lf", 3.14); |
| 181 | // |
| 182 | // Spans with "const" and pointers |
| 183 | // ------------------------------- |
| 184 | // |
| 185 | // Const and pointers can get confusing. Here are vectors of pointers and their |
| 186 | // corresponding spans: |
| 187 | // |
| 188 | // const std::vector<int*> => base::span<int* const> |
| 189 | // std::vector<const int*> => base::span<const int*> |
| 190 | // const std::vector<const int*> => base::span<const int* const> |
| 191 | // |
| 192 | // Differences from the C++20 draft |
| 193 | // -------------------------------- |
| 194 | // |
| 195 | // http://eel.is/c++draft/views contains the latest C++20 draft of std::span. |
| 196 | // Chromium tries to follow the draft as close as possible. Differences between |
| 197 | // the draft and the implementation are documented in subsections below. |
| 198 | // |
| 199 | // Differences from [span.objectrep]: |
| 200 | // - as_bytes() and as_writable_bytes() return spans of uint8_t instead of |
| 201 | // std::byte (std::byte is a C++17 feature) |
| 202 | // |
| 203 | // Differences from [span.cons]: |
| 204 | // - Constructing a static span (i.e. Extent != dynamic_extent) from a dynamic |
| 205 | // sized container (e.g. std::vector) requires an explicit conversion (in the |
| 206 | // C++20 draft this is simply UB) |
| 207 | // |
| 208 | // Differences from [span.obs]: |
| 209 | // - empty() is marked with WARN_UNUSED_RESULT instead of [[nodiscard]] |
| 210 | // ([[nodiscard]] is a C++17 feature) |
| 211 | // |
| 212 | // Furthermore, all constructors and methods are marked noexcept due to the lack |
| 213 | // of exceptions in Chromium. |
| 214 | // |
| 215 | // Due to the lack of class template argument deduction guides in C++14 |
| 216 | // appropriate make_span() utility functions are provided. |
| 217 |
| 218 | // [span], class template span |
| 219 | template <typename T, size_t Extent> |
| 220 | class span : public internal::ExtentStorage<Extent> { |
| 221 | private: |
| 222 | using ExtentStorage = internal::ExtentStorage<Extent>; |
| 223 |
| 224 | public: |
| 225 | using element_type = T; |
| 226 | using value_type = std::remove_cv_t<T>; |
| 227 | using size_type = size_t; |
| 228 | using difference_type = ptrdiff_t; |
| 229 | using pointer = T*; |
| 230 | using reference = T&; |
| 231 | using iterator = CheckedContiguousIterator<T>; |
| 232 | // TODO(https://crbug.com/828324): Drop the const_iterator typedef once gMock |
| 233 | // supports containers without this nested type. |
| 234 | using const_iterator = iterator; |
| 235 | using reverse_iterator = std::reverse_iterator<iterator>; |
| 236 | static constexpr size_t extent = Extent; |
| 237 |
| 238 | // [span.cons], span constructors, copy, assignment, and destructor |
| 239 | constexpr span() noexcept : ExtentStorage(0), data_(nullptr) { |
| 240 | static_assert(Extent == dynamic_extent || Extent == 0, "Invalid Extent"); |
| 241 | } |
| 242 |
| 243 | constexpr span(T* data, size_t size) noexcept |
| 244 | : ExtentStorage(size), data_(data) { |
| 245 | CHECK(Extent == dynamic_extent || Extent == size); |
| 246 | } |
| 247 |
| 248 | // Artificially templatized to break ambiguity for span(ptr, 0). |
| 249 | template <typename = void> |
| 250 | constexpr span(T* begin, T* end) noexcept : span(begin, end - begin) { |
| 251 | // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. |
| 252 | CHECK(begin <= end); |
| 253 | } |
| 254 |
| 255 | template < |
| 256 | size_t N, |
| 257 | typename = internal::EnableIfSpanCompatibleArray<T (&)[N], T, Extent>> |
| 258 | constexpr span(T (&array)[N]) noexcept : span(base::data(array), N) {} |
| 259 |
| 260 | template < |
| 261 | typename U, |
| 262 | size_t N, |
| 263 | typename = |
| 264 | internal::EnableIfSpanCompatibleArray<std::array<U, N>&, T, Extent>> |
| 265 | constexpr span(std::array<U, N>& array) noexcept |
| 266 | : span(base::data(array), N) {} |
| 267 |
| 268 | template <typename U, |
| 269 | size_t N, |
| 270 | typename = internal:: |
| 271 | EnableIfSpanCompatibleArray<const std::array<U, N>&, T, Extent>> |
| 272 | constexpr span(const std::array<U, N>& array) noexcept |
| 273 | : span(base::data(array), N) {} |
| 274 |
| 275 | // Conversion from a container that has compatible base::data() and integral |
| 276 | // base::size(). |
| 277 | template < |
| 278 | typename Container, |
| 279 | typename = |
| 280 | internal::EnableIfSpanCompatibleContainerAndSpanIsDynamic<Container&, |
| 281 | T, |
| 282 | Extent>> |
| 283 | constexpr span(Container& container) noexcept |
| 284 | : span(base::data(container), base::size(container)) {} |
| 285 |
| 286 | template < |
| 287 | typename Container, |
| 288 | typename = internal::EnableIfSpanCompatibleContainerAndSpanIsDynamic< |
| 289 | const Container&, |
| 290 | T, |
| 291 | Extent>> |
| 292 | constexpr span(const Container& container) noexcept |
| 293 | : span(base::data(container), base::size(container)) {} |
| 294 |
| 295 | constexpr span(const span& other) noexcept = default; |
| 296 |
| 297 | // Conversions from spans of compatible types and extents: this allows a |
| 298 | // span<T> to be seamlessly used as a span<const T>, but not the other way |
| 299 | // around. If extent is not dynamic, OtherExtent has to be equal to Extent. |
| 300 | template < |
| 301 | typename U, |
| 302 | size_t OtherExtent, |
| 303 | typename = |
| 304 | internal::EnableIfLegalSpanConversion<U, OtherExtent, T, Extent>> |
| 305 | constexpr span(const span<U, OtherExtent>& other) |
| 306 | : span(other.data(), other.size()) {} |
| 307 |
| 308 | constexpr span& operator=(const span& other) noexcept = default; |
| 309 | ~span() noexcept = default; |
| 310 |
| 311 | // [span.sub], span subviews |
| 312 | template <size_t Count> |
| 313 | constexpr span<T, Count> first() const noexcept { |
| 314 | static_assert(Count <= Extent, "Count must not exceed Extent"); |
| 315 | CHECK(Extent != dynamic_extent || Count <= size()); |
| 316 | return {data(), Count}; |
| 317 | } |
| 318 |
| 319 | template <size_t Count> |
| 320 | constexpr span<T, Count> last() const noexcept { |
| 321 | static_assert(Count <= Extent, "Count must not exceed Extent"); |
| 322 | CHECK(Extent != dynamic_extent || Count <= size()); |
| 323 | return {data() + (size() - Count), Count}; |
| 324 | } |
| 325 |
| 326 | template <size_t Offset, size_t Count = dynamic_extent> |
| 327 | constexpr span<T, |
| 328 | (Count != dynamic_extent |
| 329 | ? Count |
| 330 | : (Extent != dynamic_extent ? Extent - Offset |
| 331 | : dynamic_extent))> |
| 332 | subspan() const noexcept { |
| 333 | static_assert(Offset <= Extent, "Offset must not exceed Extent"); |
| 334 | static_assert(Count == dynamic_extent || Count <= Extent - Offset, |
| 335 | "Count must not exceed Extent - Offset"); |
| 336 | CHECK(Extent != dynamic_extent || Offset <= size()); |
| 337 | CHECK(Extent != dynamic_extent || Count == dynamic_extent || |
| 338 | Count <= size() - Offset); |
| 339 | return {data() + Offset, Count != dynamic_extent ? Count : size() - Offset}; |
| 340 | } |
| 341 |
| 342 | constexpr span<T, dynamic_extent> first(size_t count) const noexcept { |
| 343 | // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. |
| 344 | CHECK(count <= size()); |
| 345 | return {data(), count}; |
| 346 | } |
| 347 |
| 348 | constexpr span<T, dynamic_extent> last(size_t count) const noexcept { |
| 349 | // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. |
| 350 | CHECK(count <= size()); |
| 351 | return {data() + (size() - count), count}; |
| 352 | } |
| 353 |
| 354 | constexpr span<T, dynamic_extent> subspan(size_t offset, |
| 355 | size_t count = dynamic_extent) const |
| 356 | noexcept { |
| 357 | // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. |
| 358 | CHECK(offset <= size()); |
| 359 | CHECK(count == dynamic_extent || count <= size() - offset); |
| 360 | return {data() + offset, count != dynamic_extent ? count : size() - offset}; |
| 361 | } |
| 362 |
| 363 | // [span.obs], span observers |
| 364 | constexpr size_t size() const noexcept { return ExtentStorage::size(); } |
| 365 | constexpr size_t size_bytes() const noexcept { return size() * sizeof(T); } |
| 366 | constexpr bool empty() const noexcept WARN_UNUSED_RESULT { |
| 367 | return size() == 0; |
| 368 | } |
| 369 |
| 370 | // [span.elem], span element access |
| 371 | constexpr T& operator[](size_t idx) const noexcept { |
| 372 | // Note: CHECK_LT is not constexpr, hence regular CHECK must be used. |
| 373 | CHECK(idx < size()); |
| 374 | return *(data() + idx); |
| 375 | } |
| 376 |
| 377 | constexpr T& front() const noexcept { |
| 378 | static_assert(Extent == dynamic_extent || Extent > 0, |
| 379 | "Extent must not be 0"); |
| 380 | CHECK(Extent != dynamic_extent || !empty()); |
| 381 | return *data(); |
| 382 | } |
| 383 |
| 384 | constexpr T& back() const noexcept { |
| 385 | static_assert(Extent == dynamic_extent || Extent > 0, |
| 386 | "Extent must not be 0"); |
| 387 | CHECK(Extent != dynamic_extent || !empty()); |
| 388 | return *(data() + size() - 1); |
| 389 | } |
| 390 |
| 391 | constexpr T* data() const noexcept { return data_; } |
| 392 |
| 393 | // [span.iter], span iterator support |
| 394 | constexpr iterator begin() const noexcept { |
| 395 | return iterator(data_, data_ + size()); |
| 396 | } |
| 397 |
| 398 | constexpr iterator end() const noexcept { |
| 399 | return iterator(data_, data_ + size(), data_ + size()); |
| 400 | } |
| 401 |
| 402 | constexpr reverse_iterator rbegin() const noexcept { |
| 403 | return reverse_iterator(end()); |
| 404 | } |
| 405 |
| 406 | constexpr reverse_iterator rend() const noexcept { |
| 407 | return reverse_iterator(begin()); |
| 408 | } |
| 409 |
| 410 | private: |
| 411 | T* data_; |
| 412 | }; |
| 413 |
| 414 | // span<T, Extent>::extent can not be declared inline prior to C++17, hence this |
| 415 | // definition is required. |
| 416 | template <class T, size_t Extent> |
| 417 | constexpr size_t span<T, Extent>::extent; |
| 418 |
| 419 | // [span.objectrep], views of object representation |
| 420 | template <typename T, size_t X> |
| 421 | span<const uint8_t, (X == dynamic_extent ? dynamic_extent : sizeof(T) * X)> |
| 422 | as_bytes(span<T, X> s) noexcept { |
| 423 | return {reinterpret_cast<const uint8_t*>(s.data()), s.size_bytes()}; |
| 424 | } |
| 425 |
| 426 | template <typename T, |
| 427 | size_t X, |
| 428 | typename = std::enable_if_t<!std::is_const<T>::value>> |
| 429 | span<uint8_t, (X == dynamic_extent ? dynamic_extent : sizeof(T) * X)> |
| 430 | as_writable_bytes(span<T, X> s) noexcept { |
| 431 | return {reinterpret_cast<uint8_t*>(s.data()), s.size_bytes()}; |
| 432 | } |
| 433 |
| 434 | // Type-deducing helpers for constructing a span. |
| 435 | template <int&... ExplicitArgumentBarrier, typename T> |
| 436 | constexpr span<T> make_span(T* data, size_t size) noexcept { |
| 437 | return {data, size}; |
| 438 | } |
| 439 |
| 440 | template <int&... ExplicitArgumentBarrier, typename T> |
| 441 | constexpr span<T> make_span(T* begin, T* end) noexcept { |
| 442 | return {begin, end}; |
| 443 | } |
| 444 |
| 445 | // make_span utility function that deduces both the span's value_type and extent |
| 446 | // from the passed in argument. |
| 447 | // |
| 448 | // Usage: auto span = base::make_span(...); |
| 449 | template <int&... ExplicitArgumentBarrier, typename Container> |
| 450 | constexpr auto make_span(Container&& container) noexcept { |
| 451 | using T = |
| 452 | std::remove_pointer_t<decltype(base::data(std::declval<Container>()))>; |
| 453 | using Extent = internal::Extent<Container>; |
| 454 | return span<T, Extent::value>(std::forward<Container>(container)); |
| 455 | } |
| 456 |
| 457 | // make_span utility function that allows callers to explicit specify the span's |
| 458 | // extent, the value_type is deduced automatically. This is useful when passing |
| 459 | // a dynamically sized container to a method expecting static spans, when the |
| 460 | // container is known to have the correct size. |
| 461 | // |
| 462 | // Note: This will CHECK that N indeed matches size(container). |
| 463 | // |
| 464 | // Usage: auto static_span = base::make_span<N>(...); |
| 465 | template <size_t N, int&... ExplicitArgumentBarrier, typename Container> |
| 466 | constexpr auto make_span(Container&& container) noexcept { |
| 467 | using T = |
| 468 | std::remove_pointer_t<decltype(base::data(std::declval<Container>()))>; |
| 469 | return span<T, N>(base::data(container), base::size(container)); |
| 470 | } |
| 471 |
| 472 | } // namespace base |
| 473 |
| 474 | #endif // BASE_CONTAINERS_SPAN_H_ |
| 475 |