aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/io/trygvis/btree/HeapFile.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/io/trygvis/btree/HeapFile.java')
-rw-r--r--src/main/java/io/trygvis/btree/HeapFile.java58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/main/java/io/trygvis/btree/HeapFile.java b/src/main/java/io/trygvis/btree/HeapFile.java
new file mode 100644
index 0000000..7a960c8
--- /dev/null
+++ b/src/main/java/io/trygvis/btree/HeapFile.java
@@ -0,0 +1,58 @@
+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 void writePage(HeapPage page) throws IOException {
+ long position;
+ if (page.pageNumber == -1) {
+ position = file.length();
+ } else {
+ position = page.pageNumber * PAGE_SIZE;
+ }
+ channel.write(page.bytes, position);
+ channel.force(true);
+ }
+
+ public long pageCount() throws IOException {
+ return file.length() / PAGE_SIZE;
+ }
+
+ public HeapPage blankPage() {
+ return blankHeapPage(allocateDirect(PAGE_SIZE));
+ }
+}