// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_CONTAINERS_SPAN_H_ #define BASE_CONTAINERS_SPAN_H_ #include #include #include #include #include #include #include "base/logging.h" #include "base/stl_util.h" namespace base { // [views.constants] constexpr size_t dynamic_extent = static_cast(-1); template class span; namespace internal { template struct IsSpanImpl : std::false_type {}; template struct IsSpanImpl> : std::true_type {}; template using IsSpan = IsSpanImpl>; template struct IsStdArrayImpl : std::false_type {}; template struct IsStdArrayImpl> : std::true_type {}; template using IsStdArray = IsStdArrayImpl>; template using IsCArray = std::is_array>; template using IsLegalDataConversion = std::is_convertible; template using ContainerHasConvertibleData = IsLegalDataConversion< std::remove_pointer_t()))>, T>; template using ContainerHasIntegralSize = std::is_integral()))>; template using EnableIfLegalSpanConversion = std::enable_if_t<(ToExtent == dynamic_extent || ToExtent == FromExtent) && IsLegalDataConversion::value>; // SFINAE check if Array can be converted to a span. template using EnableIfSpanCompatibleArray = std::enable_if_t<(Extent == dynamic_extent || Extent == N) && ContainerHasConvertibleData::value>; // SFINAE check if Container can be converted to a span. template using EnableIfSpanCompatibleContainer = std::enable_if_t::value && !internal::IsStdArray::value && !internal::IsCArray::value && ContainerHasConvertibleData::value && ContainerHasIntegralSize::value>; // A helper template for storing the size of a span. Spans with static extents // don't require additional storage, since the extent itself is specified in the // template parameter. template class ExtentStorage { public: constexpr explicit ExtentStorage(size_t size) noexcept {} constexpr size_t size() const noexcept { return Extent; } }; // Specialization of ExtentStorage for dynamic extents, which do require // explicit storage for the size. template <> struct ExtentStorage { constexpr explicit ExtentStorage(size_t size) noexcept : size_(size) {} constexpr size_t size() const noexcept { return size_; } private: size_t size_; }; } // namespace internal // A span is a value type that represents an array of elements of type T. Since // it only consists of a pointer to memory with an associated size, it is very // light-weight. It is cheap to construct, copy, move and use spans, so that // users are encouraged to use it as a pass-by-value parameter. A span does not // own the underlying memory, so care must be taken to ensure that a span does // not outlive the backing store. // // span is somewhat analogous to StringPiece, but with arbitrary element types, // allowing mutation if T is non-const. // // span is implicitly convertible from C++ arrays, as well as most [1] // container-like types that provide a data() and size() method (such as // std::vector). A mutable span can also be implicitly converted to an // immutable span. // // Consider using a span for functions that take a data pointer and size // parameter: it allows the function to still act on an array-like type, while // allowing the caller code to be a bit more concise. // // For read-only data access pass a span: the caller can supply either // a span or a span, while the callee will have a read-only view. // For read-write access a mutable span is required. // // Without span: // Read-Only: // // std::string HexEncode(const uint8_t* data, size_t size); // std::vector data_buffer = GenerateData(); // std::string r = HexEncode(data_buffer.data(), data_buffer.size()); // // Mutable: // // ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, Args...); // char str_buffer[100]; // SafeSNPrintf(str_buffer, sizeof(str_buffer), "Pi ~= %lf", 3.14); // // With span: // Read-Only: // // std::string HexEncode(base::span data); // std::vector data_buffer = GenerateData(); // std::string r = HexEncode(data_buffer); // // Mutable: // // ssize_t SafeSNPrintf(base::span, const char* fmt, Args...); // char str_buffer[100]; // SafeSNPrintf(str_buffer, "Pi ~= %lf", 3.14); // // Spans with "const" and pointers // ------------------------------- // // Const and pointers can get confusing. Here are vectors of pointers and their // corresponding spans: // // const std::vector => base::span // std::vector => base::span // const std::vector => base::span // // Differences from the working group proposal // ------------------------------------------- // // https://wg21.link/P0122 is the latest working group proposal, Chromium // currently implements R7. Differences between the proposal and the // implementation are documented in subsections below. // // Differences from [span.objectrep]: // - as_bytes() and as_writable_bytes() return spans of uint8_t instead of // std::byte // // Differences in constants and types: // - index_type is aliased to size_t // // Differences from [span.sub]: // - using size_t instead of ptrdiff_t for indexing // // Differences from [span.obs]: // - using size_t instead of ptrdiff_t to represent size() // // Differences from [span.elem]: // - using size_t instead of ptrdiff_t for indexing // // Furthermore, all constructors and methods are marked noexcept due to the lack // of exceptions in Chromium. // // Due to the lack of class template argument deduction guides in C++14 // appropriate make_span() utility functions are provided. // [span], class template span template class span : public internal::ExtentStorage { private: using ExtentStorage = internal::ExtentStorage; public: using element_type = T; using value_type = std::remove_cv_t; using index_type = size_t; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; using iterator = T*; using const_iterator = const T*; using reverse_iterator = std::reverse_iterator; using const_reverse_iterator = std::reverse_iterator; static constexpr index_type extent = Extent; // [span.cons], span constructors, copy, assignment, and destructor constexpr span() noexcept : ExtentStorage(0), data_(nullptr) { static_assert(Extent == dynamic_extent || Extent == 0, "Invalid Extent"); } constexpr span(T* data, size_t size) noexcept : ExtentStorage(size), data_(data) { CHECK(Extent == dynamic_extent || Extent == size); } // Artificially templatized to break ambiguity for span(ptr, 0). template constexpr span(T* begin, T* end) noexcept : span(begin, end - begin) { // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. CHECK(begin <= end); } template < size_t N, typename = internal::EnableIfSpanCompatibleArray> constexpr span(T (&array)[N]) noexcept : span(base::data(array), N) {} template < size_t N, typename = internal:: EnableIfSpanCompatibleArray&, N, T, Extent>> constexpr span(std::array& array) noexcept : span(base::data(array), N) {} template &, N, T, Extent>> constexpr span(const std::array& array) noexcept : span(base::data(array), N) {} // Conversion from a container that has compatible base::data() and integral // base::size(). template > constexpr span(Container& container) noexcept : span(base::data(container), base::size(container)) {} template < typename Container, typename = internal::EnableIfSpanCompatibleContainer> span(const Container& container) noexcept : span(base::data(container), base::size(container)) {} constexpr span(const span& other) noexcept = default; // Conversions from spans of compatible types and extents: this allows a // span to be seamlessly used as a span, but not the other way // around. If extent is not dynamic, OtherExtent has to be equal to Extent. template < typename U, size_t OtherExtent, typename = internal::EnableIfLegalSpanConversion> constexpr span(const span& other) : span(other.data(), other.size()) {} constexpr span& operator=(const span& other) noexcept = default; ~span() noexcept = default; // [span.sub], span subviews template constexpr span first() const noexcept { static_assert(Extent == dynamic_extent || Count <= Extent, "Count must not exceed Extent"); CHECK(Extent != dynamic_extent || Count <= size()); return {data(), Count}; } template constexpr span last() const noexcept { static_assert(Extent == dynamic_extent || Count <= Extent, "Count must not exceed Extent"); CHECK(Extent != dynamic_extent || Count <= size()); return {data() + (size() - Count), Count}; } template constexpr span subspan() const noexcept { static_assert(Extent == dynamic_extent || Offset <= Extent, "Offset must not exceed Extent"); static_assert(Extent == dynamic_extent || Count == dynamic_extent || Count <= Extent - Offset, "Count must not exceed Extent - Offset"); CHECK(Extent != dynamic_extent || Offset <= size()); CHECK(Extent != dynamic_extent || Count == dynamic_extent || Count <= size() - Offset); return {data() + Offset, Count != dynamic_extent ? Count : size() - Offset}; } constexpr span first(size_t count) const noexcept { // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. CHECK(count <= size()); return {data(), count}; } constexpr span last(size_t count) const noexcept { // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. CHECK(count <= size()); return {data() + (size() - count), count}; } constexpr span subspan(size_t offset, size_t count = dynamic_extent) const noexcept { // Note: CHECK_LE is not constexpr, hence regular CHECK must be used. CHECK(offset <= size()); CHECK(count == dynamic_extent || count <= size() - offset); return {data() + offset, count != dynamic_extent ? count : size() - offset}; } // [span.obs], span observers constexpr size_t size() const noexcept { return ExtentStorage::size(); } constexpr size_t size_bytes() const noexcept { return size() * sizeof(T); } constexpr bool empty() const noexcept { return size() == 0; } // [span.elem], span element access constexpr T& operator[](size_t idx) const noexcept { // Note: CHECK_LT is not constexpr, hence regular CHECK must be used. CHECK(idx < size()); return *(data() + idx); } constexpr T& operator()(size_t idx) const noexcept { // Note: CHECK_LT is not constexpr, hence regular CHECK must be used. CHECK(idx < size()); return *(data() + idx); } constexpr T* data() const noexcept { return data_; } // [span.iter], span iterator support constexpr iterator begin() const noexcept { return data(); } constexpr iterator end() const noexcept { return data() + size(); } constexpr const_iterator cbegin() const noexcept { return begin(); } constexpr const_iterator cend() const noexcept { return end(); } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator(end()); } constexpr reverse_iterator rend() const noexcept { return reverse_iterator(begin()); } constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } private: T* data_; }; // span::extent can not be declared inline prior to C++17, hence this // definition is required. template constexpr size_t span::extent; // [span.comparison], span comparison operators // Relational operators. Equality is a element-wise comparison. template constexpr bool operator==(span lhs, span rhs) noexcept { return std::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()); } template constexpr bool operator!=(span lhs, span rhs) noexcept { return !(lhs == rhs); } template constexpr bool operator<(span lhs, span rhs) noexcept { return std::lexicographical_compare(lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()); } template constexpr bool operator<=(span lhs, span rhs) noexcept { return !(rhs < lhs); } template constexpr bool operator>(span lhs, span rhs) noexcept { return rhs < lhs; } template constexpr bool operator>=(span lhs, span rhs) noexcept { return !(lhs < rhs); } // [span.objectrep], views of object representation template span as_bytes(span s) noexcept { return {reinterpret_cast(s.data()), s.size_bytes()}; } template ::value>> span as_writable_bytes(span s) noexcept { return {reinterpret_cast(s.data()), s.size_bytes()}; } // Type-deducing helpers for constructing a span. template constexpr span make_span(T* data, size_t size) noexcept { return {data, size}; } template constexpr span make_span(T* begin, T* end) noexcept { return {begin, end}; } template constexpr span make_span(T (&array)[N]) noexcept { return array; } template constexpr span make_span(std::array& array) noexcept { return array; } template constexpr span make_span(const std::array& array) noexcept { return array; } template > constexpr span make_span(Container& container) noexcept { return container; } template < typename Container, typename T = const typename Container::value_type, typename = internal::EnableIfSpanCompatibleContainer> constexpr span make_span(const Container& container) noexcept { return container; } template constexpr span make_span(const span& span) noexcept { return span; } } // namespace base #endif // BASE_CONTAINERS_SPAN_H_