浏览代码

LibCore: Add helper functions to read/write trivial values from streams

Co-Authored-By: Andrew Kaster <akaster@serenityos.org>
Tim Schumacher 2 年之前
父节点
当前提交
202175cf4c
共有 1 个文件被更改,包括 16 次插入0 次删除
  1. 16 0
      Userland/Libraries/LibCore/Stream.h

+ 16 - 0
Userland/Libraries/LibCore/Stream.h

@@ -108,6 +108,22 @@ public:
         return !write_entire_buffer(buffer).is_error();
     }
 
+    template<typename T>
+    requires(IsTriviallyDestructible<T>)
+    ErrorOr<T> read_trivial_value()
+    {
+        alignas(T) u8 buffer[sizeof(T)] = {};
+        TRY(read_entire_buffer(buffer));
+        return *bit_cast<T>(buffer);
+    }
+
+    template<typename T>
+    requires(IsTriviallyDestructible<T>)
+    ErrorOr<void> 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