From bbdf766fb0157fc8481de5ae84f3ccf9f870e6d5 Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Wed, 22 Nov 2023 09:41:12 -0700 Subject: [PATCH] AK: Add helpers to convert arbitrary Spans to {Readonly}Bytes The streams and other common APIs require byte spans to operate on arbitrary data. This is less than helpful when wanting to serialize spans of other data types, such as from an Array or Vector of u32s. --- AK/Span.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/AK/Span.h b/AK/Span.h index 6816797cf77..efa23636fb3 100644 --- a/AK/Span.h +++ b/AK/Span.h @@ -322,6 +322,20 @@ using ReadonlySpan = Span; using ReadonlyBytes = ReadonlySpan; using Bytes = Span; +template +requires(IsTrivial) +ReadonlyBytes to_readonly_bytes(Span span) +{ + return ReadonlyBytes { static_cast(span.data()), span.size() * sizeof(T) }; +} + +template +requires(IsTrivial && !IsConst) +Bytes to_bytes(Span span) +{ + return Bytes { static_cast(span.data()), span.size() * sizeof(T) }; +} + } #if USING_AK_GLOBALLY @@ -329,4 +343,6 @@ using AK::Bytes; using AK::ReadonlyBytes; using AK::ReadonlySpan; using AK::Span; +using AK::to_bytes; +using AK::to_readonly_bytes; #endif