Skip to content

Commit afd170d

Browse files
Lubrsigmta
authored andcommitted
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.
1 parent b15f442 commit afd170d

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

AK/Span.h

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,24 @@ class Span : public Detail::Span<T> {
354354
}
355355
return {};
356356
}
357+
358+
template<typename TargetType>
359+
ALWAYS_INLINE constexpr Span<TargetType> reinterpret()
360+
{
361+
if constexpr (sizeof(T) % sizeof(TargetType) != 0)
362+
VERIFY((size() * sizeof(T)) % sizeof(TargetType) == 0);
363+
364+
return Span<TargetType> { reinterpret_cast<TargetType*>(data()), (size() * sizeof(T)) / sizeof(TargetType) };
365+
}
366+
367+
template<typename TargetType>
368+
ALWAYS_INLINE constexpr Span<TargetType const> reinterpret() const
369+
{
370+
if constexpr (sizeof(T) % sizeof(TargetType) != 0)
371+
VERIFY((size() * sizeof(T)) % sizeof(TargetType) == 0);
372+
373+
return Span<TargetType const> { reinterpret_cast<TargetType const*>(data()), (size() * sizeof(T)) / sizeof(TargetType) };
374+
}
357375
};
358376

359377
template<typename T>
@@ -381,14 +399,14 @@ template<typename T>
381399
requires(IsTrivial<T>)
382400
ReadonlyBytes to_readonly_bytes(Span<T> span)
383401
{
384-
return ReadonlyBytes { static_cast<void const*>(span.data()), span.size() * sizeof(T) };
402+
return span.template reinterpret<u8 const>();
385403
}
386404

387405
template<typename T>
388406
requires(IsTrivial<T> && !IsConst<T>)
389407
Bytes to_bytes(Span<T> span)
390408
{
391-
return Bytes { static_cast<void*>(span.data()), span.size() * sizeof(T) };
409+
return span.template reinterpret<u8>();
392410
}
393411

394412
}

0 commit comments

Comments
 (0)