CavalliumDBEngine/src/main/java/it/cavallium/dbengine/client/MappedSerializer.java

34 lines
1.1 KiB
Java
Raw Normal View History

package it.cavallium.dbengine.client;
2021-09-17 16:56:28 +02:00
import io.net5.buffer.api.Buffer;
import io.net5.buffer.api.Send;
2021-08-22 21:23:22 +02:00
import it.cavallium.dbengine.database.serialization.SerializationException;
import it.cavallium.dbengine.database.serialization.Serializer;
import org.jetbrains.annotations.NotNull;
2021-09-22 18:33:28 +02:00
import org.jetbrains.annotations.Nullable;
2021-09-02 17:15:40 +02:00
public class MappedSerializer<A, B> implements Serializer<B> {
2021-09-02 17:15:40 +02:00
private final Serializer<A> serializer;
private final Mapper<A, B> keyMapper;
2021-09-02 17:15:40 +02:00
public MappedSerializer(Serializer<A> serializer,
Mapper<A, B> keyMapper) {
this.serializer = serializer;
this.keyMapper = keyMapper;
}
@Override
public @NotNull DeserializationResult<B> deserialize(@NotNull Send<Buffer> serialized) throws SerializationException {
2021-08-31 09:14:46 +02:00
try (serialized) {
2021-09-02 17:15:40 +02:00
var deserialized = serializer.deserialize(serialized);
return new DeserializationResult<>(keyMapper.map(deserialized.deserializedData()), deserialized.bytesRead());
}
}
@Override
public @NotNull Send<Buffer> serialize(@NotNull B deserialized) throws SerializationException {
return serializer.serialize(keyMapper.unmap(deserialized));
}
}