strangedb/src/main/java/org/warp/cowdb/database/DatabaseFileIO.java

65 lines
1.7 KiB
Java

package org.warp.cowdb.database;
import org.warp.cowdb.IFileIO;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
public class DatabaseFileIO implements IFileIO {
private final SeekableByteChannel dataFileChannel;
private final Object dataAccessLock = new Object();
private long firstFreeIndex;
public DatabaseFileIO(Path dataFile) throws IOException {
synchronized (dataAccessLock) {
dataFileChannel = Files.newByteChannel(dataFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
firstFreeIndex = dataFileChannel.size();
}
}
@Override
public ByteBuffer readAt(long index, int length) throws IOException {
ByteBuffer dataBuffer = ByteBuffer.allocate(length);
dataFileChannel.position(index).read(dataBuffer);
dataBuffer.flip();
return dataBuffer;
}
@Override
public void writeAt(long index, int length, ByteBuffer data) throws IOException {
synchronized (dataAccessLock) {
if (data.position() != 0) {
throw new IOException("You didn't flip the ByteBuffer!");
}
if (firstFreeIndex < index + length) {
firstFreeIndex = index + length;
}
dataFileChannel.position(index).write(data);
}
}
@Override
public long writeAtEnd(int length, ByteBuffer data) throws IOException {
synchronized (dataAccessLock) {
long index = firstFreeIndex;
firstFreeIndex += length;
writeAt(index, length, data);
return index;
}
}
@Override
public void close() throws IOException {
synchronized (dataAccessLock) {
dataFileChannel.close();
}
}
}