mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-12-08 06:09:58 +00:00
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:
parent
b15f4424f9
commit
afd170d16c
Notes:
github-actions[bot]
2025-10-20 14:27:49 +00:00
Author: https://github.com/Lubrsi
Commit: afd170d16c
Pull-request: https://github.com/LadybirdBrowser/ladybird/pull/6520
Reviewed-by: https://github.com/gmta ✅
1 changed files with 20 additions and 2 deletions
22
AK/Span.h
22
AK/Span.h
|
|
@ -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>();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue