Changeset View
Changeset View
Standalone View
Standalone View
src/span.h
// Copyright (c) 2018 The Bitcoin Core developers | // Copyright (c) 2018 The Bitcoin Core developers | ||||
// Distributed under the MIT software license, see the accompanying | // Distributed under the MIT software license, see the accompanying | ||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php. | // file COPYING or http://www.opensource.org/licenses/mit-license.php. | ||||
#ifndef BITCOIN_SPAN_H | #ifndef BITCOIN_SPAN_H | ||||
#define BITCOIN_SPAN_H | #define BITCOIN_SPAN_H | ||||
#include <algorithm> | #include <algorithm> | ||||
#include <cassert> | #include <cassert> | ||||
#include <cstddef> | #include <cstddef> | ||||
#include <cstdint> | |||||
#include <type_traits> | #include <type_traits> | ||||
#ifdef DEBUG | #ifdef DEBUG | ||||
#define CONSTEXPR_IF_NOT_DEBUG | #define CONSTEXPR_IF_NOT_DEBUG | ||||
#define ASSERT_IF_DEBUG(x) assert((x)) | #define ASSERT_IF_DEBUG(x) assert((x)) | ||||
#else | #else | ||||
#define CONSTEXPR_IF_NOT_DEBUG constexpr | #define CONSTEXPR_IF_NOT_DEBUG constexpr | ||||
#define ASSERT_IF_DEBUG(x) | #define ASSERT_IF_DEBUG(x) | ||||
▲ Show 20 Lines • Show All 171 Lines • ▼ Show 20 Lines | |||||
template <typename T> T &SpanPopBack(Span<T> &span) { | template <typename T> T &SpanPopBack(Span<T> &span) { | ||||
size_t size = span.size(); | size_t size = span.size(); | ||||
ASSERT_IF_DEBUG(size > 0); | ASSERT_IF_DEBUG(size > 0); | ||||
T &back = span[size - 1]; | T &back = span[size - 1]; | ||||
span = Span<T>(span.data(), size - 1); | span = Span<T>(span.data(), size - 1); | ||||
return back; | return back; | ||||
} | } | ||||
// Helper functions to safely cast to uint8_t pointers. | |||||
inline uint8_t *UCharCast(char *c) { | |||||
return (uint8_t *)c; | |||||
} | |||||
inline uint8_t *UCharCast(uint8_t *c) { | |||||
return c; | |||||
} | |||||
inline const uint8_t *UCharCast(const char *c) { | |||||
return (uint8_t *)c; | |||||
} | |||||
inline const uint8_t *UCharCast(const uint8_t *c) { | |||||
return c; | |||||
} | |||||
// Helper function to safely convert a Span to a Span<[const] uint8_t>. | |||||
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()}; | |||||
} | |||||
/** Like MakeSpan, but for (const) uint8_t member types only. Only works | |||||
* for (un)signed char containers. */ | |||||
template <typename V> | |||||
constexpr auto MakeUCharSpan(V &&v) | |||||
-> decltype(UCharSpanCast(MakeSpan(std::forward<V>(v)))) { | |||||
return UCharSpanCast(MakeSpan(std::forward<V>(v))); | |||||
} | |||||
#endif // BITCOIN_SPAN_H | #endif // BITCOIN_SPAN_H |