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

72 lines
1.9 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 com.google.common.primitives.Longs;
import it.cavallium.dbengine.database.LLKeyValueDatabaseStructure;
import it.cavallium.dbengine.database.LLSingleton;
import it.cavallium.dbengine.database.LLSnapshot;
2021-11-12 02:05:44 +01:00
import it.cavallium.dbengine.database.UpdateReturnMode;
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 DatabaseLong implements LLKeyValueDatabaseStructure {
2020-12-07 22:15:18 +01:00
private final LLSingleton singleton;
public DatabaseLong(LLSingleton singleton) {
2020-12-07 22:15:18 +01:00
this.singleton = singleton;
}
2021-01-30 10:52:14 +01:00
public Mono<Long> get(@Nullable LLSnapshot snapshot) {
return singleton.get(snapshot).map(array -> {
if (array.length == 4) {
return (long) Ints.fromByteArray(array);
} else {
return Longs.fromByteArray(array);
}
});
2020-12-07 22:15:18 +01:00
}
2021-11-12 02:05:44 +01:00
public Mono<Long> incrementAndGet() {
return incrementAnd(UpdateReturnMode.GET_NEW_VALUE);
}
public Mono<Long> getAndIncrement() {
return incrementAnd(UpdateReturnMode.GET_OLD_VALUE);
}
private Mono<Long> incrementAnd(UpdateReturnMode updateReturnMode) {
return singleton.update(prev -> {
if (prev != null) {
try (var prevBuf = prev.receive()) {
var prevLong = prevBuf.readLong();
var alloc = singleton.getAllocator();
try (var buf = alloc.allocate(Long.BYTES)) {
buf.writeLong(prevLong + 1);
return buf;
}
}
} else {
var alloc = singleton.getAllocator();
try (var buf = alloc.allocate(Long.BYTES)) {
buf.writeLong(1);
return buf;
}
}
}, updateReturnMode).map(send -> {
try (var buf = send.receive()) {
return buf.readLong();
}
}).single();
}
2021-01-30 10:52:14 +01:00
public Mono<Void> set(long value) {
return singleton.set(Longs.toByteArray(value));
2020-12-07 22:15:18 +01:00
}
@Override
public String getDatabaseName() {
return singleton.getDatabaseName();
}
}