package io.trygvis.btree; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import static io.trygvis.btree.HeapPage.blankHeapPage; import static java.nio.ByteBuffer.allocateDirect; public class HeapFile implements Closeable { private final int PAGE_SIZE; private final RandomAccessFile file; private final FileChannel channel; public HeapFile(int PAGE_SIZE, File file) throws IOException { this.PAGE_SIZE = PAGE_SIZE; this.file = new RandomAccessFile(file, "rw"); channel = this.file.getChannel(); } @Override public void close() throws IOException { channel.force(true); file.close(); } public HeapPage loadPage(int page) throws IOException { ByteBuffer buffer = allocateDirect(PAGE_SIZE); channel.read(buffer, page * PAGE_SIZE); return HeapPage.heapPageFromBytes(page, buffer); } public long writePage(HeapPage page) throws IOException { long position; if (page.pageNumber == -1) { position = channel.size(); } else { position = page.pageNumber * PAGE_SIZE; } page.bytes.rewind(); channel.write(page.bytes, position); channel.force(true); return position / PAGE_SIZE; } public long pageCount() throws IOException { return file.length() / PAGE_SIZE; } public HeapPage blankPage() { return blankHeapPage(allocateDirect(PAGE_SIZE)); } }