109 lines
2.0 KiB
Java
109 lines
2.0 KiB
Java
package org.warp.jcwdb;
|
|
|
|
import java.io.IOException;
|
|
import java.util.function.Function;
|
|
|
|
/**
|
|
* You must have only a maximum of 1 reference for each index
|
|
* @param <T>
|
|
*/
|
|
public class EntryReference<T> implements Castable {
|
|
private final JCWDatabase.EntryReferenceTools db;
|
|
private final long entryIndex;
|
|
private final DBTypeParser<T> parser;
|
|
private T value;
|
|
private volatile boolean closed;
|
|
private final Object closeLock = new Object();
|
|
|
|
public EntryReference(JCWDatabase.EntryReferenceTools db, long entryId, DBTypeParser<T> parser) throws IOException {
|
|
this.db = db;
|
|
this.entryIndex = entryId;
|
|
this.parser = parser;
|
|
this.value = db.read(entryId, parser.getReader());
|
|
}
|
|
|
|
public EntryReference(JCWDatabase.EntryReferenceTools db, long entryId, DBTypeParser<T> parser, T value) {
|
|
this.db = db;
|
|
this.entryIndex = entryId;
|
|
this.parser = parser;
|
|
this.value = value;
|
|
}
|
|
|
|
public DBTypeParser<T> getParser() {
|
|
return parser;
|
|
}
|
|
|
|
public long getIndex() {
|
|
return entryIndex;
|
|
}
|
|
|
|
public long calculateHash() {
|
|
return parser.calculateHash(value);
|
|
}
|
|
|
|
/**
|
|
* Note that this method won't be called when closing without saving
|
|
* @throws IOException
|
|
*/
|
|
public void save() throws IOException {
|
|
if (!closed) {
|
|
db.write(entryIndex, parser.getWriter(value));
|
|
}
|
|
}
|
|
|
|
public void editValue(Function<T, T> editFunction) throws IOException {
|
|
this.value = editFunction.apply(this.value);
|
|
this.save();
|
|
}
|
|
|
|
/**
|
|
* Use editValue instead
|
|
* @return
|
|
*/
|
|
@Deprecated()
|
|
public T getValue() {
|
|
return this.value;
|
|
}
|
|
|
|
/**
|
|
* DO NOT ATTEMPT TO MODIFY THE VALUE RETURNED
|
|
* @return
|
|
*/
|
|
public T getValueUnsafe() {
|
|
return this.value;
|
|
}
|
|
|
|
@Override
|
|
public <T> T cast() {
|
|
return (T) this;
|
|
}
|
|
|
|
protected void close() throws IOException {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
synchronized (closeLock) {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
|
|
save();
|
|
|
|
closed = true;
|
|
}
|
|
}
|
|
|
|
public void closeWithoutSaving() {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
synchronized (closeLock) {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
|
|
closed = true;
|
|
}
|
|
}
|
|
}
|