package it.cavallium.dbengine.database.serialization; import io.netty.buffer.api.Buffer; import io.netty.buffer.api.BufferAllocator; import io.netty.buffer.api.Send; import it.cavallium.dbengine.database.LLUtils; import java.nio.charset.StandardCharsets; import org.jetbrains.annotations.NotNull; public interface Serializer { @NotNull A deserialize(@NotNull B serialized) throws SerializationException; @NotNull B serialize(@NotNull A deserialized) throws SerializationException; Serializer, Send> NOOP_SERIALIZER = new Serializer<>() { @Override public @NotNull Send deserialize(@NotNull Send serialized) { return serialized; } @Override public @NotNull Send serialize(@NotNull Send deserialized) { return deserialized; } }; static Serializer, Send> noop() { return NOOP_SERIALIZER; } static Serializer> utf8(BufferAllocator allocator) { return new Serializer<>() { @Override public @NotNull String deserialize(@NotNull Send serializedToReceive) { try (Buffer serialized = serializedToReceive.receive()) { int length = serialized.readInt(); return LLUtils.deserializeString(serialized.send(), serialized.readerOffset(), length, StandardCharsets.UTF_8); } } @Override public @NotNull Send serialize(@NotNull String deserialized) { var bytes = deserialized.getBytes(StandardCharsets.UTF_8); try (Buffer buf = allocator.allocate(Integer.BYTES + bytes.length)) { buf.writeInt(bytes.length); buf.writeBytes(bytes); return buf.send(); } } }; } }