Browse Source

LibCore: Add support for non-trivial types to `Stream::*_value`

At the moment, there is no immediate advantage compared to just calling
the underlying functions directly, but having a common interface feels
more ergonomic (users don't have to care about how a type serializes)
and maybe we'll find a way to hide the actual implementation from direct
access some time in the future.
Tim Schumacher 2 years ago
parent
commit
6ccda76a71
1 changed files with 14 additions and 0 deletions
  1. 14 0
      Userland/Libraries/LibCore/Stream.h

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

@@ -101,6 +101,13 @@ public:
     /// contents are written or an error occurs.
     virtual ErrorOr<void> write_entire_buffer(ReadonlyBytes);
 
+    template<typename T>
+    requires(requires(Stream& stream) { { T::read_from_stream(stream) } -> SameAs<ErrorOr<T>>; })
+    ErrorOr<T> read_value()
+    {
+        return T::read_from_stream(*this);
+    }
+
     template<typename T>
     requires(Traits<T>::is_trivially_serializable())
     ErrorOr<T> read_value()
@@ -110,6 +117,13 @@ public:
         return bit_cast<T>(buffer);
     }
 
+    template<typename T>
+    requires(requires(T t, Stream& stream) { { t.write_to_stream(stream) } -> SameAs<ErrorOr<void>>; })
+    ErrorOr<void> write_value(T const& value)
+    {
+        return value.write_to_stream(*this);
+    }
+
     template<typename T>
     requires(Traits<T>::is_trivially_serializable())
     ErrorOr<void> write_value(T const& value)