From 202175cf4ca423648c5c4b3b2d795984d181276e Mon Sep 17 00:00:00 2001 From: Tim Schumacher Date: Mon, 9 Jan 2023 18:39:44 +0100 Subject: [PATCH] LibCore: Add helper functions to read/write trivial values from streams Co-Authored-By: Andrew Kaster --- Userland/Libraries/LibCore/Stream.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Userland/Libraries/LibCore/Stream.h b/Userland/Libraries/LibCore/Stream.h index 66546b3462..2023cc304e 100644 --- a/Userland/Libraries/LibCore/Stream.h +++ b/Userland/Libraries/LibCore/Stream.h @@ -108,6 +108,22 @@ public: return !write_entire_buffer(buffer).is_error(); } + template + requires(IsTriviallyDestructible) + ErrorOr read_trivial_value() + { + alignas(T) u8 buffer[sizeof(T)] = {}; + TRY(read_entire_buffer(buffer)); + return *bit_cast(buffer); + } + + template + requires(IsTriviallyDestructible) + ErrorOr write_trivial_value(T const& value) + { + return write_entire_buffer({ &value, sizeof(value) }); + } + /// Returns whether the stream has reached the end of file. For sockets, /// this most likely means that the protocol has disconnected (in the case /// of TCP). For seekable streams, this means the end of the file. Note that