From a9a00624590ecbb8ab493538875b6b73a1a09299 Mon Sep 17 00:00:00 2001 From: Dillon Nys Date: Wed, 21 Feb 2024 08:07:25 -0800 Subject: [PATCH] chore: Add inline serializer factory --- .../lib/src/serialization/serializer.dart | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/packages/celest_core/lib/src/serialization/serializer.dart b/packages/celest_core/lib/src/serialization/serializer.dart index d863fda6..b2f00735 100644 --- a/packages/celest_core/lib/src/serialization/serializer.dart +++ b/packages/celest_core/lib/src/serialization/serializer.dart @@ -20,6 +20,17 @@ abstract base class Serializer { /// {@macro celest_core.serialization.serializer} const Serializer(); + /// Defines a [Serializer] for a [Dart] type with the given [serialize] and + /// [deserialize] methods. + static Serializer define({ + required Object? Function(Dart value) serialize, + required Dart Function(Wire value) deserialize, + }) => + _Serializer( + serialize: serialize, + deserialize: deserialize, + ); + /// Serializes [value] to the wire type. Object? serialize(Dart value); @@ -43,6 +54,26 @@ abstract base class Serializer { } } +final class _Serializer + extends Serializer { + const _Serializer({ + required Object? Function(Dart value) serialize, + required Dart Function(Wire value) deserialize, + }) : _serialize = serialize, + _deserialize = deserialize; + + final Object? Function(Dart value) _serialize; + final Dart Function(Wire value) _deserialize; + + @override + Object? serialize(Dart value) => _serialize(value); + + @override + Dart deserialize(Object? value) => _deserialize( + assertWireType(value), + ); +} + typedef _Nullable = T?; bool _isNullable() => null is T;