2021-02-02 19:40:37 +01:00
|
|
|
package it.cavallium.dbengine.database.serialization;
|
|
|
|
|
2023-02-09 23:34:25 +01:00
|
|
|
import it.cavallium.dbengine.buffers.Buf;
|
|
|
|
import it.cavallium.dbengine.buffers.BufDataInput;
|
|
|
|
import it.cavallium.dbengine.buffers.BufDataOutput;
|
2021-04-30 19:15:04 +02:00
|
|
|
import java.nio.charset.StandardCharsets;
|
2021-02-02 19:40:37 +01:00
|
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
|
2021-09-01 00:01:56 +02:00
|
|
|
public interface Serializer<A> {
|
2021-02-02 19:40:37 +01:00
|
|
|
|
2023-02-09 23:34:25 +01:00
|
|
|
@NotNull A deserialize(@NotNull BufDataInput in) throws SerializationException;
|
2021-02-02 19:40:37 +01:00
|
|
|
|
2023-02-09 23:34:25 +01:00
|
|
|
void serialize(@NotNull A deserialized, BufDataOutput out) throws SerializationException;
|
2021-02-02 19:40:37 +01:00
|
|
|
|
2021-10-19 00:22:05 +02:00
|
|
|
/**
|
|
|
|
* @return suggested default buffer size, -1 if unknown
|
|
|
|
*/
|
|
|
|
int getSerializedSizeHint();
|
2021-09-01 00:01:56 +02:00
|
|
|
|
2023-02-09 23:34:25 +01:00
|
|
|
Serializer<Buf> NOOP_SERIALIZER = new Serializer<>() {
|
2021-03-14 03:13:19 +01:00
|
|
|
@Override
|
2023-02-09 23:34:25 +01:00
|
|
|
public @NotNull Buf deserialize(@NotNull BufDataInput in) {
|
|
|
|
return Buf.wrap(in.readAllBytes());
|
2021-10-19 00:22:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2023-02-09 23:34:25 +01:00
|
|
|
public void serialize(@NotNull Buf deserialized, BufDataOutput out) {
|
|
|
|
out.writeBytes(deserialized);
|
2021-03-14 03:13:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2021-10-19 00:22:05 +02:00
|
|
|
public int getSerializedSizeHint() {
|
|
|
|
return -1;
|
2021-03-14 03:13:19 +01:00
|
|
|
}
|
|
|
|
};
|
2021-02-02 19:40:37 +01:00
|
|
|
|
2021-10-19 00:22:05 +02:00
|
|
|
Serializer<String> UTF8_SERIALIZER = new Serializer<>() {
|
2023-02-09 23:34:25 +01:00
|
|
|
|
|
|
|
@Override
|
|
|
|
public @NotNull String deserialize(@NotNull BufDataInput in) throws SerializationException {
|
|
|
|
int length = in.readInt();
|
|
|
|
var bytes = in.readNBytes(length);
|
|
|
|
return new String(bytes, StandardCharsets.UTF_8);
|
2021-05-03 21:41:51 +02:00
|
|
|
}
|
2021-10-19 00:22:05 +02:00
|
|
|
|
2023-02-09 23:34:25 +01:00
|
|
|
@Override
|
|
|
|
public void serialize(@NotNull String deserialized, BufDataOutput out) throws SerializationException {
|
|
|
|
var bytes = deserialized.getBytes(StandardCharsets.UTF_8);
|
|
|
|
out.ensureWritable(Integer.BYTES + bytes.length);
|
|
|
|
out.writeInt(bytes.length);
|
|
|
|
out.write(bytes);
|
2021-10-19 00:22:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public int getSerializedSizeHint() {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
};
|
2021-02-02 19:40:37 +01:00
|
|
|
}
|