CavalliumDBEngine/src/main/java/it/cavallium/dbengine/database/collections/DatabaseInt.java

49 lines
1.5 KiB
Java
Raw Normal View History

2021-01-30 22:14:48 +01:00
package it.cavallium.dbengine.database.collections;
2020-12-07 22:15:18 +01:00
import com.google.common.primitives.Ints;
import it.cavallium.dbengine.database.LLKeyValueDatabaseStructure;
import it.cavallium.dbengine.database.LLSingleton;
import it.cavallium.dbengine.database.LLSnapshot;
2022-06-20 12:30:33 +02:00
import it.cavallium.dbengine.database.LLUtils;
2022-03-20 14:33:27 +01:00
import it.cavallium.dbengine.database.serialization.SerializationException;
import it.cavallium.dbengine.database.serialization.SerializerFixedBinaryLength;
2020-12-07 22:15:18 +01:00
import org.jetbrains.annotations.Nullable;
2021-01-30 10:52:14 +01:00
import reactor.core.publisher.Mono;
2020-12-07 22:15:18 +01:00
public class DatabaseInt implements LLKeyValueDatabaseStructure {
2020-12-07 22:15:18 +01:00
private final LLSingleton singleton;
2022-03-20 14:33:27 +01:00
private final SerializerFixedBinaryLength<Integer> serializer;
2020-12-07 22:15:18 +01:00
public DatabaseInt(LLSingleton singleton) {
2020-12-07 22:15:18 +01:00
this.singleton = singleton;
2022-03-20 14:33:27 +01:00
this.serializer = SerializerFixedBinaryLength.intSerializer(singleton.getAllocator());
2020-12-07 22:15:18 +01:00
}
2021-01-30 10:52:14 +01:00
public Mono<Integer> get(@Nullable LLSnapshot snapshot) {
2022-05-26 13:13:14 +02:00
var resultMono = singleton.get(snapshot);
return Mono.usingWhen(resultMono,
result -> Mono.fromSupplier(() -> serializer.deserialize(result)),
2022-06-20 12:30:33 +02:00
LLUtils::finalizeResource
2022-05-26 13:13:14 +02:00
);
2020-12-07 22:15:18 +01:00
}
2021-01-30 10:52:14 +01:00
public Mono<Void> set(int value) {
2022-03-20 14:33:27 +01:00
return singleton.set(Mono.fromCallable(() -> {
var buf = singleton.getAllocator().allocate(Integer.BYTES);
try {
2022-03-20 14:33:27 +01:00
serializer.serialize(value, buf);
return buf;
} catch (Throwable ex) {
buf.close();
throw ex;
2022-03-20 14:33:27 +01:00
}
}));
2020-12-07 22:15:18 +01:00
}
@Override
public String getDatabaseName() {
return singleton.getDatabaseName();
}
}