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 { record DeserializationResult(T deserializedData, int bytesRead) {} @NotNull DeserializationResult deserialize(@NotNull Send serialized) throws SerializationException; @NotNull Send serialize(@NotNull A deserialized) throws SerializationException; Serializer> NOOP_SERIALIZER = new Serializer<>() { @Override public @NotNull DeserializationResult> deserialize(@NotNull Send serialized) { try (var serializedBuf = serialized.receive()) { var readableBytes = serializedBuf.readableBytes(); return new DeserializationResult<>(serializedBuf.send(), readableBytes); } } @Override public @NotNull Send serialize(@NotNull Send deserialized) { return deserialized; } }; static Serializer> noop() { return NOOP_SERIALIZER; } static Serializer utf8(BufferAllocator allocator) { return new Serializer<>() { @Override public @NotNull DeserializationResult deserialize(@NotNull Send serializedToReceive) { try (Buffer serialized = serializedToReceive.receive()) { int length = serialized.readInt(); var readerOffset = serialized.readerOffset(); var readableBytes = serialized.readableBytes(); return new DeserializationResult<>(LLUtils.deserializeString(serialized.send(), readerOffset, length, StandardCharsets.UTF_8), readableBytes); } } @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(); } } }; } }