dash/src/span.h
Wladimir J. van der Laan 4bb1132438
Merge #12886: Introduce Span type and use it instead of FLATDATA
9272d70 Support serializing Span<unsigned char> and use that instead of FLATDATA (Pieter Wuille)
833bc08 Add Slice: a (pointer, size) array view that acts like a container (Pieter Wuille)

Pull request description:

  Introduce a new data type `Span`, which is an encapsulated pointer + size (like C++20's `std::span` or LevelDB's `Slice`), and represents a view to a sequence of objects laid out continuously in memory.

  The immediate use case is replacing the remaining `FLATDATA` invocations. Instead of those, we support serializing/deserializing unsigned char `Span`s (treating them as arrays).

  A longer term goal for `Span`s is making the script execution operate on them rather than on `CScript` itself. This will allow separate storage mechanisms for scripts.

Tree-SHA512: 7b0da3c802e5df367f223275004d16b04262804c007b7c73fda927176f0a9c3b2ef3225fa842cb73500b0df73175ec1419f1f5239de2402e21dd9ae8e5d05233
2020-12-17 11:21:20 +03:00

41 lines
1.4 KiB
C++

// Copyright (c) 2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SPAN_H
#define BITCOIN_SPAN_H
#include <type_traits>
#include <cstddef>
/** A Span is an object that can refer to a contiguous sequence of objects.
*
* It implements a subset of C++20's std::span.
*/
template<typename C>
class Span
{
C* m_data;
std::ptrdiff_t m_size;
public:
constexpr Span() noexcept : m_data(nullptr), m_size(0) {}
constexpr Span(C* data, std::ptrdiff_t size) noexcept : m_data(data), m_size(size) {}
constexpr C* data() const noexcept { return m_data; }
constexpr std::ptrdiff_t size() const noexcept { return m_size; }
};
/** Create a span to a container exposing data() and size().
*
* This correctly deals with constness: the returned Span's element type will be
* whatever data() returns a pointer to. If either the passed container is const,
* or its element type is const, the resulting span will have a const element type.
*
* std::span will have a constructor that implements this functionality directly.
*/
template<typename V>
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()); }
#endif