From afd170d16c0a2425be17ebfd83df84de079a9b0f Mon Sep 17 00:00:00 2001 From: Luke Wilde Date: Mon, 20 Oct 2025 13:13:22 +0100 Subject: [PATCH] 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. --- AK/Span.h | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/AK/Span.h b/AK/Span.h index aacce9c711..af3fa077ab 100644 --- a/AK/Span.h +++ b/AK/Span.h @@ -354,6 +354,24 @@ public: } return {}; } + + template + ALWAYS_INLINE constexpr Span reinterpret() + { + if constexpr (sizeof(T) % sizeof(TargetType) != 0) + VERIFY((size() * sizeof(T)) % sizeof(TargetType) == 0); + + return Span { reinterpret_cast(data()), (size() * sizeof(T)) / sizeof(TargetType) }; + } + + template + ALWAYS_INLINE constexpr Span reinterpret() const + { + if constexpr (sizeof(T) % sizeof(TargetType) != 0) + VERIFY((size() * sizeof(T)) % sizeof(TargetType) == 0); + + return Span { reinterpret_cast(data()), (size() * sizeof(T)) / sizeof(TargetType) }; + } }; template @@ -381,14 +399,14 @@ template requires(IsTrivial) ReadonlyBytes to_readonly_bytes(Span span) { - return ReadonlyBytes { static_cast(span.data()), span.size() * sizeof(T) }; + return span.template reinterpret(); } template requires(IsTrivial && !IsConst) Bytes to_bytes(Span span) { - return Bytes { static_cast(span.data()), span.size() * sizeof(T) }; + return span.template reinterpret(); } }