From e63dcc3a6752e7d406e7a650c2d6c2e95cd39aab Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Thu, 18 Jun 2020 16:31:08 -0700 Subject: [PATCH] Add MakeUCharSpan, to help constructing Span<[const] unsigned char> Based on a suggestion by Russell Yanofsky. --- src/span.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/span.h b/src/span.h index 79f13c92032..4afb383a594 100644 --- a/src/span.h +++ b/src/span.h @@ -207,4 +207,16 @@ T& SpanPopBack(Span& span) return back; } +// Helper functions to safely cast to unsigned char pointers. +inline unsigned char* UCharCast(char* c) { return (unsigned char*)c; } +inline unsigned char* UCharCast(unsigned char* c) { return c; } +inline const unsigned char* UCharCast(const char* c) { return (unsigned char*)c; } +inline const unsigned char* UCharCast(const unsigned char* c) { return c; } + +// Helper function to safely convert a Span to a Span<[const] unsigned char>. +template constexpr auto UCharSpanCast(Span s) -> Span::type> { return {UCharCast(s.data()), s.size()}; } + +/** Like MakeSpan, but for (const) unsigned char member types only. Only works for (un)signed char containers. */ +template constexpr auto MakeUCharSpan(V&& v) -> decltype(UCharSpanCast(MakeSpan(std::forward(v)))) { return UCharSpanCast(MakeSpan(std::forward(v))); } + #endif