Skip to content

Commit

Permalink
chore: Add inline serializer factory
Browse files Browse the repository at this point in the history
  • Loading branch information
dnys1 committed Feb 27, 2024
1 parent 4eb672d commit a9a0062
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions packages/celest_core/lib/src/serialization/serializer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ abstract base class Serializer<Dart extends Object?> {
/// {@macro celest_core.serialization.serializer}
const Serializer();

/// Defines a [Serializer] for a [Dart] type with the given [serialize] and
/// [deserialize] methods.
static Serializer<Dart> define<Dart extends Object?, Wire extends Object?>({
required Object? Function(Dart value) serialize,
required Dart Function(Wire value) deserialize,
}) =>
_Serializer<Dart, Wire>(
serialize: serialize,
deserialize: deserialize,
);

/// Serializes [value] to the wire type.
Object? serialize(Dart value);

Expand All @@ -43,6 +54,26 @@ abstract base class Serializer<Dart extends Object?> {
}
}

final class _Serializer<Dart extends Object?, Wire extends Object?>
extends Serializer<Dart> {
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<Wire>(value),
);
}

typedef _Nullable<T> = T?;
bool _isNullable<T>() => null is T;

Expand Down

0 comments on commit a9a0062

Please sign in to comment.