Line data Source code
1 : // Copyright (c) 2018-2020 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 <type_traits>
9 : #include <cstddef>
10 : #include <algorithm>
11 : #include <assert.h>
12 :
13 : #ifdef DEBUG
14 : #define CONSTEXPR_IF_NOT_DEBUG
15 : #define ASSERT_IF_DEBUG(x) assert((x))
16 : #else
17 : #define CONSTEXPR_IF_NOT_DEBUG constexpr
18 : #define ASSERT_IF_DEBUG(x)
19 : #endif
20 :
21 : /** A Span is an object that can refer to a contiguous sequence of objects.
22 : *
23 : * It implements a subset of C++20's std::span.
24 : *
25 : * Things to be aware of when writing code that deals with Spans:
26 : *
27 : * - Similar to references themselves, Spans are subject to reference lifetime
28 : * issues. The user is responsible for making sure the objects pointed to by
29 : * a Span live as long as the Span is used. For example:
30 : *
31 : * std::vector<int> vec{1,2,3,4};
32 : * Span<int> sp(vec);
33 : * vec.push_back(5);
34 : * printf("%i\n", sp.front()); // UB!
35 : *
36 : * may exhibit undefined behavior, as increasing the size of a vector may
37 : * invalidate references.
38 : *
39 : * - One particular pitfall is that Spans can be constructed from temporaries,
40 : * but this is unsafe when the Span is stored in a variable, outliving the
41 : * temporary. For example, this will compile, but exhibits undefined behavior:
42 : *
43 : * Span<const int> sp(std::vector<int>{1, 2, 3});
44 : * printf("%i\n", sp.front()); // UB!
45 : *
46 : * The lifetime of the vector ends when the statement it is created in ends.
47 : * Thus the Span is left with a dangling reference, and using it is undefined.
48 : *
49 : * - Due to Span's automatic creation from range-like objects (arrays, and data
50 : * types that expose a data() and size() member function), functions that
51 : * accept a Span as input parameter can be called with any compatible
52 : * range-like object. For example, this works:
53 : *
54 : * void Foo(Span<const int> arg);
55 : *
56 : * Foo(std::vector<int>{1, 2, 3}); // Works
57 : *
58 : * This is very useful in cases where a function truly does not care about the
59 : * container, and only about having exactly a range of elements. However it
60 : * may also be surprising to see automatic conversions in this case.
61 : *
62 : * When a function accepts a Span with a mutable element type, it will not
63 : * accept temporaries; only variables or other references. For example:
64 : *
65 : * void FooMut(Span<int> arg);
66 : *
67 : * FooMut(std::vector<int>{1, 2, 3}); // Does not compile
68 : * std::vector<int> baz{1, 2, 3};
69 : * FooMut(baz); // Works
70 : *
71 : * This is similar to how functions that take (non-const) lvalue references
72 : * as input cannot accept temporaries. This does not work either:
73 : *
74 : * void FooVec(std::vector<int>& arg);
75 : * FooVec(std::vector<int>{1, 2, 3}); // Does not compile
76 : *
77 : * The idea is that if a function accepts a mutable reference, a meaningful
78 : * result will be present in that variable after the call. Passing a temporary
79 : * is useless in that context.
80 : */
81 : template<typename C>
82 : class Span
83 : {
84 : C* m_data;
85 : std::size_t m_size;
86 :
87 : public:
88 4 : constexpr Span() noexcept : m_data(nullptr), m_size(0) {}
89 :
90 : /** Construct a span from a begin pointer and a size.
91 : *
92 : * This implements a subset of the iterator-based std::span constructor in C++20,
93 : * which is hard to implement without std::address_of.
94 : */
95 : template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0>
96 23261270 : constexpr Span(T* begin, std::size_t size) noexcept : m_data(begin), m_size(size) {}
97 :
98 : /** Construct a span from a begin and end pointer.
99 : *
100 : * This implements a subset of the iterator-based std::span constructor in C++20,
101 : * which is hard to implement without std::address_of.
102 : */
103 : template <typename T, typename std::enable_if<std::is_convertible<T (*)[], C (*)[]>::value, int>::type = 0>
104 20298 : CONSTEXPR_IF_NOT_DEBUG Span(T* begin, T* end) noexcept : m_data(begin), m_size(end - begin)
105 10149 : {
106 : ASSERT_IF_DEBUG(end >= begin);
107 20298 : }
108 :
109 : /** Implicit conversion of spans between compatible types.
110 : *
111 : * Specifically, if a pointer to an array of type O can be implicitly converted to a pointer to an array of type
112 : * C, then permit implicit conversion of Span<O> to Span<C>. This matches the behavior of the corresponding
113 : * C++20 std::span constructor.
114 : *
115 : * For example this means that a Span<T> can be converted into a Span<const T>.
116 : */
117 : template <typename O, typename std::enable_if<std::is_convertible<O (*)[], C (*)[]>::value, int>::type = 0>
118 : constexpr Span(const Span<O>& other) noexcept : m_data(other.m_data), m_size(other.m_size) {}
119 :
120 : /** Default copy constructor. */
121 : constexpr Span(const Span&) noexcept = default;
122 :
123 : /** Default assignment operator. */
124 : Span& operator=(const Span& other) noexcept = default;
125 :
126 : /** Construct a Span from an array. This matches the corresponding C++20 std::span constructor. */
127 : template <int N>
128 13026705 : constexpr Span(C (&a)[N]) noexcept : m_data(a), m_size(N) {}
129 :
130 : /** Construct a Span for objects with .data() and .size() (std::string, std::array, std::vector, ...).
131 : *
132 : * This implements a subset of the functionality provided by the C++20 std::span range-based constructor.
133 : *
134 : * To prevent surprises, only Spans for constant value types are supported when passing in temporaries.
135 : * Note that this restriction does not exist when converting arrays or other Spans (see above).
136 : */
137 : template <typename V, typename std::enable_if<(std::is_const<C>::value || std::is_lvalue_reference<V>::value) && std::is_convertible<typename std::remove_pointer<decltype(std::declval<V&>().data())>::type (*)[], C (*)[]>::value && std::is_convertible<decltype(std::declval<V&>().size()), std::size_t>::value, int>::type = 0>
138 64701965 : constexpr Span(V&& v) noexcept : m_data(v.data()), m_size(v.size()) {}
139 :
140 42108177 : constexpr C* data() const noexcept { return m_data; }
141 7633875 : constexpr C* begin() const noexcept { return m_data; }
142 8450072 : constexpr C* end() const noexcept { return m_data + m_size; }
143 : CONSTEXPR_IF_NOT_DEBUG C& front() const noexcept
144 : {
145 : ASSERT_IF_DEBUG(size() > 0);
146 : return m_data[0];
147 : }
148 : CONSTEXPR_IF_NOT_DEBUG C& back() const noexcept
149 : {
150 : ASSERT_IF_DEBUG(size() > 0);
151 : return m_data[m_size - 1];
152 : }
153 57706705 : constexpr std::size_t size() const noexcept { return m_size; }
154 497 : constexpr bool empty() const noexcept { return size() == 0; }
155 3591336 : CONSTEXPR_IF_NOT_DEBUG C& operator[](std::size_t pos) const noexcept
156 : {
157 : ASSERT_IF_DEBUG(size() > pos);
158 3591336 : return m_data[pos];
159 : }
160 4849184 : CONSTEXPR_IF_NOT_DEBUG Span<C> subspan(std::size_t offset) const noexcept
161 : {
162 : ASSERT_IF_DEBUG(size() >= offset);
163 4849184 : return Span<C>(m_data + offset, m_size - offset);
164 : }
165 1828 : CONSTEXPR_IF_NOT_DEBUG Span<C> subspan(std::size_t offset, std::size_t count) const noexcept
166 : {
167 : ASSERT_IF_DEBUG(size() >= offset + count);
168 1828 : return Span<C>(m_data + offset, count);
169 : }
170 1668994 : CONSTEXPR_IF_NOT_DEBUG Span<C> first(std::size_t count) const noexcept
171 : {
172 : ASSERT_IF_DEBUG(size() >= count);
173 1668994 : return Span<C>(m_data, count);
174 : }
175 58 : CONSTEXPR_IF_NOT_DEBUG Span<C> last(std::size_t count) const noexcept
176 : {
177 : ASSERT_IF_DEBUG(size() >= count);
178 58 : return Span<C>(m_data + m_size - count, count);
179 : }
180 :
181 844 : friend constexpr bool operator==(const Span& a, const Span& b) noexcept { return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); }
182 : friend constexpr bool operator!=(const Span& a, const Span& b) noexcept { return !(a == b); }
183 : friend constexpr bool operator<(const Span& a, const Span& b) noexcept { return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end()); }
184 : friend constexpr bool operator<=(const Span& a, const Span& b) noexcept { return !(b < a); }
185 : friend constexpr bool operator>(const Span& a, const Span& b) noexcept { return (b < a); }
186 : friend constexpr bool operator>=(const Span& a, const Span& b) noexcept { return !(a < b); }
187 :
188 : template <typename O> friend class Span;
189 : };
190 :
191 : // MakeSpan helps constructing a Span of the right type automatically.
192 : /** MakeSpan for arrays: */
193 1654537 : template <typename A, int N> Span<A> constexpr MakeSpan(A (&a)[N]) { return Span<A>(a, N); }
194 : /** MakeSpan for temporaries / rvalue references, only supporting const output. */
195 : template <typename V> constexpr auto MakeSpan(V&& v) -> typename std::enable_if<!std::is_lvalue_reference<V>::value, Span<const typename std::remove_pointer<decltype(v.data())>::type>>::type { return std::forward<V>(v); }
196 : /** MakeSpan for (lvalue) references, supporting mutable output. */
197 3879127 : template <typename V> constexpr auto MakeSpan(V& v) -> Span<typename std::remove_pointer<decltype(v.data())>::type> { return v; }
198 :
199 : /** Pop the last element off a span, and return a reference to that element. */
200 : template <typename T>
201 17979 : T& SpanPopBack(Span<T>& span)
202 : {
203 17979 : size_t size = span.size();
204 : ASSERT_IF_DEBUG(size > 0);
205 17979 : T& back = span[size - 1];
206 17979 : span = Span<T>(span.data(), size - 1);
207 17979 : return back;
208 : }
209 :
210 : // Helper functions to safely cast to unsigned char pointers.
211 96 : inline unsigned char* UCharCast(char* c) { return (unsigned char*)c; }
212 9408 : inline unsigned char* UCharCast(unsigned char* c) { return c; }
213 80942 : inline const unsigned char* UCharCast(const char* c) { return (unsigned char*)c; }
214 3222052 : inline const unsigned char* UCharCast(const unsigned char* c) { return c; }
215 :
216 : // Helper function to safely convert a Span to a Span<[const] unsigned char>.
217 3312498 : 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()}; }
218 :
219 : /** Like MakeSpan, but for (const) unsigned char member types only. Only works for (un)signed char containers. */
220 3312500 : template <typename V> constexpr auto MakeUCharSpan(V&& v) -> decltype(UCharSpanCast(MakeSpan(std::forward<V>(v)))) { return UCharSpanCast(MakeSpan(std::forward<V>(v))); }
221 :
222 : #endif
|