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(); } }