Skip to content

Commit 833bc08

Browse files
committed
Add Slice: a (pointer, size) array view that acts like a container
1 parent bfaed1a commit 833bc08

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/Makefile.am

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ libbitcoin_consensus_a_SOURCES = \
312312
script/script_error.cpp \
313313
script/script_error.h \
314314
serialize.h \
315+
span.h \
315316
tinyformat.h \
316317
uint256.cpp \
317318
uint256.h \

src/span.h

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Copyright (c) 2018 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+
11+
/** A Span is an object that can refer to a contiguous sequence of objects.
12+
*
13+
* It implements a subset of C++20's std::span.
14+
*/
15+
template<typename C>
16+
class Span
17+
{
18+
C* m_data;
19+
std::ptrdiff_t m_size;
20+
21+
public:
22+
constexpr Span() noexcept : m_data(nullptr), m_size(0) {}
23+
constexpr Span(C* data, std::ptrdiff_t size) noexcept : m_data(data), m_size(size) {}
24+
25+
constexpr C* data() const noexcept { return m_data; }
26+
constexpr std::ptrdiff_t size() const noexcept { return m_size; }
27+
};
28+
29+
/** Create a span to a container exposing data() and size().
30+
*
31+
* This correctly deals with constness: the returned Span's element type will be
32+
* whatever data() returns a pointer to. If either the passed container is const,
33+
* or its element type is const, the resulting span will have a const element type.
34+
*
35+
* std::span will have a constructor that implements this functionality directly.
36+
*/
37+
template<typename V>
38+
constexpr Span<typename std::remove_pointer<decltype(std::declval<V>().data())>::type> MakeSpan(V& v) { return Span<typename std::remove_pointer<decltype(std::declval<V>().data())>::type>(v.data(), v.size()); }
39+
40+
#endif

0 commit comments

Comments
 (0)