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

69 lines
2.1 KiB
Java
Raw Normal View History

package it.cavallium.dbengine.database.collections;
import it.cavallium.dbengine.client.CompositeSnapshot;
import it.cavallium.dbengine.database.LLDictionary;
import it.cavallium.dbengine.database.LLDictionaryResultType;
import it.cavallium.dbengine.database.LLRange;
import it.cavallium.dbengine.database.LLSnapshot;
2021-02-02 19:40:37 +01:00
import it.cavallium.dbengine.database.serialization.Serializer;
import org.jetbrains.annotations.Nullable;
import reactor.core.publisher.Mono;
2021-01-31 19:52:47 +01:00
public class DatabaseSingle<U> implements DatabaseStageEntry<U> {
private final LLDictionary dictionary;
private final byte[] key;
private final Serializer<U, byte[]> serializer;
public DatabaseSingle(LLDictionary dictionary, byte[] key, Serializer<U, byte[]> serializer) {
this.dictionary = dictionary;
this.key = key;
2021-01-31 19:52:47 +01:00
this.serializer = serializer;
}
private LLSnapshot resolveSnapshot(@Nullable CompositeSnapshot snapshot) {
if (snapshot == null) {
return null;
} else {
return snapshot.getSnapshot(dictionary);
}
}
@Override
2021-01-31 19:52:47 +01:00
public Mono<U> get(@Nullable CompositeSnapshot snapshot) {
return dictionary.get(resolveSnapshot(snapshot), key).map(this::deserialize);
}
@Override
2021-01-31 19:52:47 +01:00
public Mono<U> setAndGetPrevious(U value) {
return dictionary.put(key, serialize(value), LLDictionaryResultType.PREVIOUS_VALUE).map(this::deserialize);
}
@Override
2021-01-31 19:52:47 +01:00
public Mono<U> clearAndGetPrevious() {
return dictionary.remove(key, LLDictionaryResultType.PREVIOUS_VALUE).map(this::deserialize);
}
@Override
public Mono<Long> size(@Nullable CompositeSnapshot snapshot, boolean fast) {
return dictionary
.isRangeEmpty(resolveSnapshot(snapshot), LLRange.single(key))
.map(empty -> empty ? 0L : 1L);
}
@Override
public Mono<Boolean> isEmpty(@Nullable CompositeSnapshot snapshot) {
return dictionary
.isRangeEmpty(resolveSnapshot(snapshot), LLRange.single(key));
}
2021-01-31 19:52:47 +01:00
//todo: temporary wrapper. convert the whole class to buffers
private U deserialize(byte[] bytes) {
return serializer.deserialize(bytes);
2021-01-31 19:52:47 +01:00
}
//todo: temporary wrapper. convert the whole class to buffers
private byte[] serialize(U bytes) {
return serializer.serialize(bytes);
2021-01-31 19:52:47 +01:00
}
}