102 lines
2.2 KiB
Java
102 lines
2.2 KiB
Java
package org.warp.cowdb.lists;
|
|
|
|
import it.unimi.dsi.fastutil.longs.LongArrayList;
|
|
import org.warp.cowdb.EnhancedObject;
|
|
import org.warp.cowdb.IDatabase;
|
|
import org.warp.jcwdb.ann.DBDataType;
|
|
import org.warp.jcwdb.ann.DBField;
|
|
|
|
import java.io.IOException;
|
|
import java.util.StringJoiner;
|
|
|
|
public abstract class CowList<T> extends EnhancedObject {
|
|
|
|
private final Object indicesAccessLock = new Object();
|
|
|
|
@DBField(id = 0, type = DBDataType.REFERENCES_LIST)
|
|
private LongArrayList indices;
|
|
|
|
public CowList() {
|
|
|
|
}
|
|
|
|
public CowList(IDatabase database) throws IOException {
|
|
super(database);
|
|
}
|
|
|
|
@Override
|
|
public void initialize() throws IOException {
|
|
indices = new LongArrayList();
|
|
}
|
|
|
|
public T get(int index) throws IOException {
|
|
synchronized (indicesAccessLock) {
|
|
long uid = indices.getLong(index);
|
|
return loadItem(uid);
|
|
}
|
|
}
|
|
|
|
public void add(T value) throws IOException {
|
|
long uid = database.getObjectsIO().newNullObject();
|
|
synchronized (indicesAccessLock) {
|
|
indices.add(uid);
|
|
writeItemToDisk(uid, value);
|
|
}
|
|
}
|
|
|
|
public void update(int index, T value) throws IOException {
|
|
synchronized (indicesAccessLock) {
|
|
set(index, value);
|
|
}
|
|
}
|
|
|
|
public void set(int index, T value) throws IOException {
|
|
long uid = database.getObjectsIO().newNullObject();
|
|
synchronized (indicesAccessLock) {
|
|
indices.set(index, uid);
|
|
writeItemToDisk(uid, value);
|
|
}
|
|
}
|
|
|
|
public void add(int index, T value) throws IOException {
|
|
long uid = database.getObjectsIO().newNullObject();
|
|
synchronized (indicesAccessLock) {
|
|
indices.add(index, uid);
|
|
writeItemToDisk(uid, value);
|
|
}
|
|
}
|
|
|
|
public T getLast() throws IOException {
|
|
synchronized (indicesAccessLock) {
|
|
if (indices.size() > 0) {
|
|
return get(indices.size() - 1);
|
|
} else {
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
|
|
public boolean isEmpty() {
|
|
synchronized (indicesAccessLock) {
|
|
return indices.size() <= 0;
|
|
}
|
|
}
|
|
|
|
public int size() {
|
|
synchronized (indicesAccessLock) {
|
|
return indices.size();
|
|
}
|
|
}
|
|
|
|
protected abstract T loadItem(long uid) throws IOException;
|
|
|
|
protected abstract void writeItemToDisk(long uid, T item) throws IOException;
|
|
|
|
@Override
|
|
public String toString() {
|
|
return new StringJoiner(", ", CowList.class.getSimpleName() + "[", "]")
|
|
.add(indices.size() + " items")
|
|
.toString();
|
|
}
|
|
}
|