diff options
author | MarcoFalke <falke.marco@gmail.com> | 2021-11-04 09:03:04 +0100 |
---|---|---|
committer | MarcoFalke <falke.marco@gmail.com> | 2021-11-09 17:42:13 +0100 |
commit | faa3ec2304051be7cfbe301cfbfbda3faf7514fc (patch) | |
tree | d4bd1d6efd163452352e275beec7674de246d9af /src/span.h | |
parent | fa18038f519db76befb9a7bd0b1540143bfeb12b (diff) |
span: Add std::byte helpers
Also, add Span<std::byte> interface to strencondings.
Diffstat (limited to 'src/span.h')
-rw-r--r-- | src/span.h | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/src/span.h b/src/span.h index 830164514b..78e8fc691d 100644 --- a/src/span.h +++ b/src/span.h @@ -180,6 +180,7 @@ public: return m_data[m_size - 1]; } constexpr std::size_t size() const noexcept { return m_size; } + constexpr std::size_t size_bytes() const noexcept { return sizeof(C) * m_size; } constexpr bool empty() const noexcept { return size() == 0; } CONSTEXPR_IF_NOT_DEBUG C& operator[](std::size_t pos) const noexcept { @@ -236,11 +237,35 @@ T& SpanPopBack(Span<T>& span) return back; } +// From C++20 as_bytes and as_writeable_bytes +template <typename T> +Span<const std::byte> AsBytes(Span<T> s) noexcept +{ + return {reinterpret_cast<const std::byte*>(s.data()), s.size_bytes()}; +} +template <typename T> +Span<std::byte> AsWritableBytes(Span<T> s) noexcept +{ + return {reinterpret_cast<std::byte*>(s.data()), s.size_bytes()}; +} + +template <typename V> +Span<const std::byte> MakeByteSpan(V&& v) noexcept +{ + return AsBytes(MakeSpan(std::forward<V>(v))); +} +template <typename V> +Span<std::byte> MakeWritableByteSpan(V&& v) noexcept +{ + return AsWritableBytes(MakeSpan(std::forward<V>(v))); +} + // 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; } +inline const unsigned char* UCharCast(const std::byte* c) { return reinterpret_cast<const unsigned char*>(c); } // Helper function to safely convert a Span to a Span<[const] unsigned char>. 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()}; } |