AK: Add the ability to reinterpret a Span to a given type

This allows you to reinterpret a Span to any given type, maintaining
the original data and working out the new size for you.

The target type must evenly fit into the Span's original type, ensuring
bytes are not dropped.
This commit is contained in:
Luke Wilde 2025-10-20 13:13:22 +01:00 committed by Jelle Raaijmakers
parent b15f4424f9
commit afd170d16c
Notes: github-actions[bot] 2025-10-20 14:27:49 +00:00

View file

@ -354,6 +354,24 @@ public:
}
return {};
}
template<typename TargetType>
ALWAYS_INLINE constexpr Span<TargetType> reinterpret()
{
if constexpr (sizeof(T) % sizeof(TargetType) != 0)
VERIFY((size() * sizeof(T)) % sizeof(TargetType) == 0);
return Span<TargetType> { reinterpret_cast<TargetType*>(data()), (size() * sizeof(T)) / sizeof(TargetType) };
}
template<typename TargetType>
ALWAYS_INLINE constexpr Span<TargetType const> reinterpret() const
{
if constexpr (sizeof(T) % sizeof(TargetType) != 0)
VERIFY((size() * sizeof(T)) % sizeof(TargetType) == 0);
return Span<TargetType const> { reinterpret_cast<TargetType const*>(data()), (size() * sizeof(T)) / sizeof(TargetType) };
}
};
template<typename T>
@ -381,14 +399,14 @@ template<typename T>
requires(IsTrivial<T>)
ReadonlyBytes to_readonly_bytes(Span<T> span)
{
return ReadonlyBytes { static_cast<void const*>(span.data()), span.size() * sizeof(T) };
return span.template reinterpret<u8 const>();
}
template<typename T>
requires(IsTrivial<T> && !IsConst<T>)
Bytes to_bytes(Span<T> span)
{
return Bytes { static_cast<void*>(span.data()), span.size() * sizeof(T) };
return span.template reinterpret<u8>();
}
}