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

86 lines
2.2 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() {
2021-11-14 22:21:32 +01:00
return addAnd(1, UpdateReturnMode.GET_NEW_VALUE);
2021-11-12 02:05:44 +01:00
}
public Mono<Long> getAndIncrement() {
2021-11-14 22:21:32 +01:00
return addAnd(1, UpdateReturnMode.GET_OLD_VALUE);
2021-11-12 02:05:44 +01:00
}
2021-11-14 22:21:32 +01:00
public Mono<Long> decrementAndGet() {
return addAnd(-1, UpdateReturnMode.GET_NEW_VALUE);
}
public Mono<Long> getAndDecrement() {
return addAnd(-1, UpdateReturnMode.GET_OLD_VALUE);
}
public Mono<Long> addAndGet(long count) {
return addAnd(count, UpdateReturnMode.GET_NEW_VALUE);
}
public Mono<Long> getAndAdd(long count) {
return addAnd(count, UpdateReturnMode.GET_OLD_VALUE);
}
private Mono<Long> addAnd(long count, UpdateReturnMode updateReturnMode) {
2021-11-12 02:05:44 +01:00
return singleton.update(prev -> {
if (prev != null) {
try (var prevBuf = prev.receive()) {
var prevLong = prevBuf.readLong();
var alloc = singleton.getAllocator();
2021-11-12 02:52:42 +01:00
var buf = alloc.allocate(Long.BYTES);
2021-11-14 22:21:32 +01:00
buf.writeLong(prevLong + count);
2021-11-12 02:52:42 +01:00
return buf;
2021-11-12 02:05:44 +01:00
}
} else {
var alloc = singleton.getAllocator();
2021-11-12 02:52:42 +01:00
var buf = alloc.allocate(Long.BYTES);
2021-11-14 22:21:32 +01:00
buf.writeLong(count);
2021-11-12 02:52:42 +01:00
return buf;
2021-11-12 02:05:44 +01:00
}
}, 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();
}
}