From 7a820294f37b9e1d361f2210295806fde5c59293 Mon Sep 17 00:00:00 2001 From: bsorrentino Date: Fri, 9 Aug 2024 23:37:33 +0200 Subject: [PATCH] feat: add utitlity for support serialization of nullable value --- .../bsc/langgraph4j/serializer/Serializer.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/core-jdk8/src/main/java/org/bsc/langgraph4j/serializer/Serializer.java b/core-jdk8/src/main/java/org/bsc/langgraph4j/serializer/Serializer.java index 15404f6..1129f7e 100644 --- a/core-jdk8/src/main/java/org/bsc/langgraph4j/serializer/Serializer.java +++ b/core-jdk8/src/main/java/org/bsc/langgraph4j/serializer/Serializer.java @@ -4,14 +4,28 @@ import java.io.*; import java.util.Objects; +import java.util.Optional; public interface Serializer { void write(T object, ObjectOutput out) throws IOException; - - T read(ObjectInput in) throws IOException, ClassNotFoundException ; + default void writeNullable(T object, ObjectOutput out) throws IOException { + if( object == null ) { + out.writeBoolean(false); + } else { + out.writeBoolean(true); + write(object, out); + } + } + default Optional readNullable(ObjectInput in) throws IOException, ClassNotFoundException { + if( in.readBoolean() ) { + return Optional.ofNullable(read(in)); + } + return Optional.empty(); + } + default byte[] writeObject(T object) throws IOException { Objects.requireNonNull( object, "object cannot be null" ); try( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) {