io.datakernel.crdt.TimestampContainer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of datakernel-crdt Show documentation
Show all versions of datakernel-crdt Show documentation
Conflict-free replicated data type implementation for DataKernel Framework.
package io.datakernel.crdt;
import io.datakernel.eventloop.Eventloop;
import io.datakernel.serializer.BinarySerializer;
import io.datakernel.serializer.util.BinaryInput;
import io.datakernel.serializer.util.BinaryOutput;
import org.jetbrains.annotations.Nullable;
import java.util.function.BinaryOperator;
public final class TimestampContainer {
private final long timestamp;
private final S state;
public TimestampContainer(long timestamp, S state) {
this.timestamp = timestamp;
this.state = state;
}
public static TimestampContainer now(S state) {
return new TimestampContainer<>(Eventloop.getCurrentEventloop().currentTimeMillis(), state);
}
public long getTimestamp() {
return timestamp;
}
public S getState() {
return state;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TimestampContainer> that = (TimestampContainer>) o;
return timestamp == that.timestamp && state.equals(that.state);
}
@Override
public int hashCode() {
return 31 * (int) (timestamp ^ (timestamp >>> 32)) + state.hashCode();
}
@Override
public String toString() {
return "[" + state + "](ts=" + timestamp + ')';
}
public static CrdtFunction> createCrdtFunction(BinaryOperator combiner) {
return new CrdtFunction>() {
@Override
public TimestampContainer merge(TimestampContainer first, TimestampContainer second) {
return new TimestampContainer<>(Math.max(first.getTimestamp(), second.getTimestamp()), combiner.apply(first.getState(), second.getState()));
}
@Nullable
@Override
public TimestampContainer extract(TimestampContainer state, long timestamp) {
if (state.getTimestamp() > timestamp) {
return state;
}
return null;
}
};
}
public static BinarySerializer> createSerializer(BinarySerializer stateSerializer) {
return new BinarySerializer>() {
@Override
public void encode(BinaryOutput out, TimestampContainer item) {
out.writeLong(item.getTimestamp());
stateSerializer.encode(out, item.getState());
}
@Override
public TimestampContainer decode(BinaryInput in) {
return new TimestampContainer<>(in.readLong(), stateSerializer.decode(in));
}
};
}
}