LCOV - code coverage report
Current view: top level - src - span.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 58 58 100.0 %
Date: 2024-05-24 08:22:33 Functions: 307 339 90.6 %
Branches: 13 28 46.4 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2018-2022 The Bitcoin Core developers
       2                 :            : // Distributed under the MIT software license, see the accompanying
       3                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :            : 
       5                 :            : #ifndef BITCOIN_SPAN_H
       6                 :            : #define BITCOIN_SPAN_H
       7                 :            : 
       8                 :            : #include <algorithm>
       9                 :            : #include <cassert>
      10                 :            : #include <cstddef>
      11                 :            : #include <span>
      12                 :            : #include <type_traits>
      13                 :            : 
      14                 :            : #ifdef DEBUG
      15                 :            : #define CONSTEXPR_IF_NOT_DEBUG
      16                 :            : #define ASSERT_IF_DEBUG(x) assert((x))
      17                 :            : #else
      18                 :            : #define CONSTEXPR_IF_NOT_DEBUG constexpr
      19                 :            : #define ASSERT_IF_DEBUG(x)
      20                 :            : #endif
      21                 :            : 
      22                 :            : #if defined(__clang__)
      23                 :            : #if __has_attribute(lifetimebound)
      24                 :            : #define SPAN_ATTR_LIFETIMEBOUND [[clang::lifetimebound]]
      25                 :            : #else
      26                 :            : #define SPAN_ATTR_LIFETIMEBOUND
      27                 :            : #endif
      28                 :            : #else
      29                 :            : #define SPAN_ATTR_LIFETIMEBOUND
      30                 :            : #endif
      31                 :            : 
      32                 :            : /** A Span is an object that can refer to a contiguous sequence of objects.
      33                 :            :  *
      34                 :            :  * This file implements a subset of C++20's std::span.  It can be considered
      35                 :            :  * temporary compatibility code until C++20 and is designed to be a
      36                 :            :  * self-contained abstraction without depending on other project files. For this
      37                 :            :  * reason, Clang lifetimebound is defined here instead of including
      38                 :            :  * <attributes.h>, which also defines it.
      39                 :            :  *
      40                 :            :  * Things to be aware of when writing code that deals with Spans:
      41                 :            :  *
      42                 :            :  * - Similar to references themselves, Spans are subject to reference lifetime
      43                 :            :  *   issues. The user is responsible for making sure the objects pointed to by
      44                 :            :  *   a Span live as long as the Span is used. For example:
      45                 :            :  *
      46                 :            :  *       std::vector<int> vec{1,2,3,4};
      47                 :            :  *       Span<int> sp(vec);
      48                 :            :  *       vec.push_back(5);
      49                 :            :  *       printf("%i\n", sp.front()); // UB!
      50                 :            :  *
      51                 :            :  *   may exhibit undefined behavior, as increasing the size of a vector may
      52                 :            :  *   invalidate references.
      53                 :            :  *
      54                 :            :  * - One particular pitfall is that Spans can be constructed from temporaries,
      55                 :            :  *   but this is unsafe when the Span is stored in a variable, outliving the
      56                 :            :  *   temporary. For example, this will compile, but exhibits undefined behavior:
      57                 :            :  *
      58                 :            :  *       Span<const int> sp(std::vector<int>{1, 2, 3});
      59                 :            :  *       printf("%i\n", sp.front()); // UB!
      60                 :            :  *
      61                 :            :  *   The lifetime of the vector ends when the statement it is created in ends.
      62                 :            :  *   Thus the Span is left with a dangling reference, and using it is undefined.
      63                 :            :  *
      64                 :            :  * - Due to Span's automatic creation from range-like objects (arrays, and data
      65                 :            :  *   types that expose a data() and size() member function), functions that
      66                 :            :  *   accept a Span as input parameter can be called with any compatible
      67                 :            :  *   range-like object. For example, this works:
      68                 :            :  *
      69                 :            :  *       void Foo(Span<const int> arg);
      70                 :            :  *
      71                 :            :  *       Foo(std::vector<int>{1, 2, 3}); // Works
      72                 :            :  *
      73                 :            :  *   This is very useful in cases where a function truly does not care about the
      74                 :            :  *   container, and only about having exactly a range of elements. However it
      75                 :            :  *   may also be surprising to see automatic conversions in this case.
      76                 :            :  *
      77                 :            :  *   When a function accepts a Span with a mutable element type, it will not
      78                 :            :  *   accept temporaries; only variables or other references. For example:
      79                 :            :  *
      80                 :            :  *       void FooMut(Span<int> arg);
      81                 :            :  *
      82                 :            :  *       FooMut(std::vector<int>{1, 2, 3}); // Does not compile
      83                 :            :  *       std::vector<int> baz{1, 2, 3};
      84                 :            :  *       FooMut(baz); // Works
      85                 :            :  *
      86                 :            :  *   This is similar to how functions that take (non-const) lvalue references
      87                 :            :  *   as input cannot accept temporaries. This does not work either:
      88                 :            :  *
      89                 :            :  *       void FooVec(std::vector<int>& arg);
      90                 :            :  *       FooVec(std::vector<int>{1, 2, 3}); // Does not compile
      91                 :            :  *
      92                 :            :  *   The idea is that if a function accepts a mutable reference, a meaningful
      93                 :            :  *   result will be present in that variable after the call. Passing a temporary
      94                 :            :  *   is useless in that context.
      95                 :            :  */
      96                 :            : template<typename C>
      97                 :            : class Span
      98                 :            : {
      99                 :            :     C* m_data;
     100                 :      22779 :     std::size_t m_size{0};
     101                 :            : 
     102                 :            :     template <class T>
     103                 :            :     struct is_Span_int : public std::false_type {};
     104                 :            :     template <class T>
     105                 :            :     struct is_Span_int<Span<T>> : public std::true_type {};
     106                 :            :     template <class T>
     107                 :            :     struct is_Span : public is_Span_int<typename std::remove_cv<T>::type>{};
     108                 :            : 
     109                 :            : 
     110                 :            : public:
     111                 :      45558 :     constexpr Span() noexcept : m_data(nullptr) {}
     112                 :            : 
     113                 :            :     /** Construct a span from a begin pointer and a size.
     114                 :            :      *
     115                 :            :      * This implements a subset of the iterator-based std::span constructor in C++20,
     116                 :            :      * which is hard to implement without std::address_of.
     117                 :            :      */
     118                 :            :     template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0>
     119                 : 7917859745 :     constexpr Span(T* begin, std::size_t size) noexcept : m_data(begin), m_size(size) {}
     120                 :            : 
     121                 :            :     /** Construct a span from a begin and end pointer.
     122                 :            :      *
     123                 :            :      * This implements a subset of the iterator-based std::span constructor in C++20,
     124                 :            :      * which is hard to implement without std::address_of.
     125                 :            :      */
     126                 :            :     template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0>
     127                 :    2160608 :     CONSTEXPR_IF_NOT_DEBUG Span(T* begin, T* end) noexcept : m_data(begin), m_size(end - begin)
     128                 :            :     {
     129                 :            :         ASSERT_IF_DEBUG(end >= begin);
     130                 :    2160608 :     }
     131                 :            : 
     132                 :            :     /** Implicit conversion of spans between compatible types.
     133                 :            :      *
     134                 :            :      *  Specifically, if a pointer to an array of type O can be implicitly converted to a pointer to an array of type
     135                 :            :      *  C, then permit implicit conversion of Span<O> to Span<C>. This matches the behavior of the corresponding
     136                 :            :      *  C++20 std::span constructor.
     137                 :            :      *
     138                 :            :      *  For example this means that a Span<T> can be converted into a Span<const T>.
     139                 :            :      */
     140                 :            :     template <typename O, typename std::enable_if<std::is_convertible<O (*)[], C (*)[]>::value, int>::type = 0>
     141                 :    6602242 :     constexpr Span(const Span<O>& other) noexcept : m_data(other.m_data), m_size(other.m_size) {}
     142                 :            : 
     143                 :            :     /** Default copy constructor. */
     144                 :            :     constexpr Span(const Span&) noexcept = default;
     145                 :            : 
     146                 :            :     /** Default assignment operator. */
     147                 :            :     Span& operator=(const Span& other) noexcept = default;
     148                 :            : 
     149                 :            :     /** Construct a Span from an array. This matches the corresponding C++20 std::span constructor. */
     150                 :            :     template <int N>
     151                 :   29141268 :     constexpr Span(C (&a)[N]) noexcept : m_data(a), m_size(N) {}
     152                 :            : 
     153                 :            :     /** Construct a Span for objects with .data() and .size() (std::string, std::array, std::vector, ...).
     154                 :            :      *
     155                 :            :      * This implements a subset of the functionality provided by the C++20 std::span range-based constructor.
     156                 :            :      *
     157                 :            :      * To prevent surprises, only Spans for constant value types are supported when passing in temporaries.
     158                 :            :      * Note that this restriction does not exist when converting arrays or other Spans (see above).
     159                 :            :      */
     160                 :            :     template <typename V>
     161                 :  274443050 :     constexpr Span(V& other SPAN_ATTR_LIFETIMEBOUND,
     162                 :            :         typename std::enable_if<!is_Span<V>::value &&
     163                 :            :                                 std::is_convertible<typename std::remove_pointer<decltype(std::declval<V&>().data())>::type (*)[], C (*)[]>::value &&
     164                 :            :                                 std::is_convertible<decltype(std::declval<V&>().size()), std::size_t>::value, std::nullptr_t>::type = nullptr)
     165                 :  274443050 :         : m_data(other.data()), m_size(other.size()){}
     166                 :            : 
     167                 :            :     template <typename V>
     168                 :  726243424 :     constexpr Span(const V& other SPAN_ATTR_LIFETIMEBOUND,
     169                 :            :         typename std::enable_if<!is_Span<V>::value &&
     170                 :            :                                 std::is_convertible<typename std::remove_pointer<decltype(std::declval<const V&>().data())>::type (*)[], C (*)[]>::value &&
     171                 :            :                                 std::is_convertible<decltype(std::declval<const V&>().size()), std::size_t>::value, std::nullptr_t>::type = nullptr)
     172                 :  726243424 :         : m_data(other.data()), m_size(other.size()){}
     173                 :            : 
     174                 : 3817473180 :     constexpr C* data() const noexcept { return m_data; }
     175                 :  391932446 :     constexpr C* begin() const noexcept { return m_data; }
     176                 :  630393325 :     constexpr C* end() const noexcept { return m_data + m_size; }
     177                 : 3849812653 :     CONSTEXPR_IF_NOT_DEBUG C& front() const noexcept
     178                 :            :     {
     179                 :            :         ASSERT_IF_DEBUG(size() > 0);
     180                 : 3849812653 :         return m_data[0];
     181                 :            :     }
     182                 :       9700 :     CONSTEXPR_IF_NOT_DEBUG C& back() const noexcept
     183                 :            :     {
     184                 :            :         ASSERT_IF_DEBUG(size() > 0);
     185                 :       9700 :         return m_data[m_size - 1];
     186                 :            :     }
     187                 : 7746689610 :     constexpr std::size_t size() const noexcept { return m_size; }
     188                 : 2187445644 :     constexpr std::size_t size_bytes() const noexcept { return sizeof(C) * m_size; }
     189                 :  132135296 :     constexpr bool empty() const noexcept { return size() == 0; }
     190                 :  498412315 :     CONSTEXPR_IF_NOT_DEBUG C& operator[](std::size_t pos) const noexcept
     191                 :            :     {
     192                 :            :         ASSERT_IF_DEBUG(size() > pos);
     193                 :  498412315 :         return m_data[pos];
     194                 :            :     }
     195                 : 4091593569 :     CONSTEXPR_IF_NOT_DEBUG Span<C> subspan(std::size_t offset) const noexcept
     196                 :            :     {
     197                 :            :         ASSERT_IF_DEBUG(size() >= offset);
     198                 : 4091593569 :         return Span<C>(m_data + offset, m_size - offset);
     199                 :            :     }
     200                 :    1860329 :     CONSTEXPR_IF_NOT_DEBUG Span<C> subspan(std::size_t offset, std::size_t count) const noexcept
     201                 :            :     {
     202                 :            :         ASSERT_IF_DEBUG(size() >= offset + count);
     203                 :    1860329 :         return Span<C>(m_data + offset, count);
     204                 :            :     }
     205                 :   23365697 :     CONSTEXPR_IF_NOT_DEBUG Span<C> first(std::size_t count) const noexcept
     206                 :            :     {
     207                 :            :         ASSERT_IF_DEBUG(size() >= count);
     208                 :   23365697 :         return Span<C>(m_data, count);
     209                 :            :     }
     210                 :   40847159 :     CONSTEXPR_IF_NOT_DEBUG Span<C> last(std::size_t count) const noexcept
     211                 :            :     {
     212                 :            :          ASSERT_IF_DEBUG(size() >= count);
     213                 :   40847159 :          return Span<C>(m_data + m_size - count, count);
     214                 :            :     }
     215                 :            : 
     216   [ +  +  +  -  :    9268347 :     friend constexpr bool operator==(const Span& a, const Span& b) noexcept { return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); }
             #  #  #  # ]
     217                 :      20074 :     friend constexpr bool operator!=(const Span& a, const Span& b) noexcept { return !(a == b); }
     218         [ +  - ]:         76 :     friend constexpr bool operator<(const Span& a, const Span& b) noexcept { return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end()); }
     219                 :         19 :     friend constexpr bool operator<=(const Span& a, const Span& b) noexcept { return !(b < a); }
     220                 :         19 :     friend constexpr bool operator>(const Span& a, const Span& b) noexcept { return (b < a); }
     221                 :         19 :     friend constexpr bool operator>=(const Span& a, const Span& b) noexcept { return !(a < b); }
     222                 :            : 
     223                 :            :     template <typename O> friend class Span;
     224                 :            : };
     225                 :            : 
     226                 :            : // Return result of calling .data() method on type T. This is used to be able to
     227                 :            : // write template deduction guides for the single-parameter Span constructor
     228                 :            : // below that will work if the value that is passed has a .data() method, and if
     229                 :            : // the data method does not return a void pointer.
     230                 :            : //
     231                 :            : // It is important to check for the void type specifically below, so the
     232                 :            : // deduction guides can be used in SFINAE contexts to check whether objects can
     233                 :            : // be converted to spans. If the deduction guides did not explicitly check for
     234                 :            : // void, and an object was passed that returned void* from data (like
     235                 :            : // std::vector<bool>), the template deduction would succeed, but the Span<void>
     236                 :            : // object instantiation would fail, resulting in a hard error, rather than a
     237                 :            : // SFINAE error.
     238                 :            : // https://stackoverflow.com/questions/68759148/sfinae-to-detect-the-explicitness-of-a-ctad-deduction-guide
     239                 :            : // https://stackoverflow.com/questions/16568986/what-happens-when-you-call-data-on-a-stdvectorbool
     240                 :            : template<typename T>
     241                 :            : using DataResult = std::remove_pointer_t<decltype(std::declval<T&>().data())>;
     242                 :            : 
     243                 :            : // Deduction guides for Span
     244                 :            : // For the pointer/size based and iterator based constructor:
     245                 :            : template <typename T, typename EndOrSize> Span(T*, EndOrSize) -> Span<T>;
     246                 :            : // For the array constructor:
     247                 :            : template <typename T, std::size_t N> Span(T (&)[N]) -> Span<T>;
     248                 :            : // For the temporaries/rvalue references constructor, only supporting const output.
     249                 :            : template <typename T> Span(T&&) -> Span<std::enable_if_t<!std::is_lvalue_reference_v<T> && !std::is_void_v<DataResult<T&&>>, const DataResult<T&&>>>;
     250                 :            : // For (lvalue) references, supporting mutable output.
     251                 :            : template <typename T> Span(T&) -> Span<std::enable_if_t<!std::is_void_v<DataResult<T&>>, DataResult<T&>>>;
     252                 :            : 
     253                 :            : /** Pop the last element off a span, and return a reference to that element. */
     254                 :            : template <typename T>
     255                 :     230124 : T& SpanPopBack(Span<T>& span)
     256                 :            : {
     257                 :     230124 :     size_t size = span.size();
     258                 :            :     ASSERT_IF_DEBUG(size > 0);
     259                 :     230124 :     T& back = span[size - 1];
     260                 :     230124 :     span = Span<T>(span.data(), size - 1);
     261                 :     460248 :     return back;
     262                 :     230124 : }
     263                 :            : 
     264                 :            : // From C++20 as_bytes and as_writeable_bytes
     265                 :            : template <typename T>
     266                 : 1709434931 : Span<const std::byte> AsBytes(Span<T> s) noexcept
     267                 :            : {
     268                 : 1709434931 :     return {reinterpret_cast<const std::byte*>(s.data()), s.size_bytes()};
     269                 :            : }
     270                 :            : template <typename T>
     271                 :  478010713 : Span<std::byte> AsWritableBytes(Span<T> s) noexcept
     272                 :            : {
     273                 :  478010713 :     return {reinterpret_cast<std::byte*>(s.data()), s.size_bytes()};
     274                 :            : }
     275                 :            : 
     276                 :            : template <typename V>
     277                 :  344673018 : Span<const std::byte> MakeByteSpan(V&& v) noexcept
     278                 :            : {
     279   [ +  -  +  -  :  344673018 :     return AsBytes(Span{std::forward<V>(v)});
          +  -  +  -  +  
                      - ]
     280                 :            : }
     281                 :            : template <typename V>
     282                 :   36880380 : Span<std::byte> MakeWritableByteSpan(V&& v) noexcept
     283                 :            : {
     284   [ +  -  +  -  :   36880380 :     return AsWritableBytes(Span{std::forward<V>(v)});
             +  -  +  - ]
     285                 :            : }
     286                 :            : 
     287                 :            : // Helper functions to safely cast basic byte pointers to unsigned char pointers.
     288                 :            : inline unsigned char* UCharCast(char* c) { return reinterpret_cast<unsigned char*>(c); }
     289                 :     366956 : inline unsigned char* UCharCast(unsigned char* c) { return c; }
     290                 :            : inline unsigned char* UCharCast(signed char* c) { return reinterpret_cast<unsigned char*>(c); }
     291                 :   99022890 : inline unsigned char* UCharCast(std::byte* c) { return reinterpret_cast<unsigned char*>(c); }
     292                 :      55633 : inline const unsigned char* UCharCast(const char* c) { return reinterpret_cast<const unsigned char*>(c); }
     293                 :   29770288 : inline const unsigned char* UCharCast(const unsigned char* c) { return c; }
     294                 :            : inline const unsigned char* UCharCast(const signed char* c) { return reinterpret_cast<const unsigned char*>(c); }
     295                 : 1006946096 : inline const unsigned char* UCharCast(const std::byte* c) { return reinterpret_cast<const unsigned char*>(c); }
     296                 :            : // Helper concept for the basic byte types.
     297                 :            : template <typename B>
     298                 :            : concept BasicByte = requires { UCharCast(std::span<B>{}.data()); };
     299                 :            : 
     300                 :            : // Helper function to safely convert a Span to a Span<[const] unsigned char>.
     301                 :   24914491 : template <typename T> constexpr auto UCharSpanCast(Span<T> s) -> Span<typename std::remove_pointer<decltype(UCharCast(s.data()))>::type> { return {UCharCast(s.data()), s.size()}; }
     302                 :            : 
     303                 :            : /** Like the Span constructor, but for (const) unsigned char member types only. Only works for (un)signed char containers. */
     304                 :   24914491 : template <typename V> constexpr auto MakeUCharSpan(V&& v) -> decltype(UCharSpanCast(Span{std::forward<V>(v)})) { return UCharSpanCast(Span{std::forward<V>(v)}); }
     305                 :            : 
     306                 :            : #endif // BITCOIN_SPAN_H

Generated by: LCOV version 1.16