// SPDX-License-Identifier: BSD-2-Clause // author: Max Kellermann #pragma once #include "CopyConst.hxx" #include #include #include #include /** * Cast a std::span to a std::span, rounding down to the * next multiple of T's size. */ template constexpr std::span FromBytesFloor(std::span> other) noexcept { static_assert(sizeof(T) > 0, "Empty base type"); /* TODO: the "void *" cast suppresses alignment warnings, but should we really suppress them? */ return { reinterpret_cast(reinterpret_cast *>(other.data())), other.size() / sizeof(T), }; } /** * Like FromBytesFloor(), but assert that rounding is not necessary. */ template constexpr std::span FromBytesStrict(std::span> other) noexcept { assert(other.size() % sizeof(T) == 0); return FromBytesFloor(other); } constexpr std::span ToSpan(std::string_view sv) noexcept { #if defined(__clang__) && __clang_major__ < 15 /* workaround for old clang/libc++ versions which can't cast std::string_view to std::span */ return {sv.data(), sv.size()}; #else return std::span{sv}; #endif } inline std::span AsBytes(std::string_view sv) noexcept { return std::as_bytes(ToSpan(sv)); } constexpr std::string_view ToStringView(std::span s) noexcept { return {s.data(), s.size()}; } constexpr std::string_view ToStringView(std::span s) noexcept { return ToStringView(FromBytesStrict(s)); } template constexpr std::basic_string_view ToStringView(std::span s) noexcept { return {s.data(), s.size()}; } template constexpr std::basic_string_view ToStringView(std::span s) noexcept { return {s.data(), s.size()}; }