diff options
Diffstat (limited to 'src/main/java/io/trygvis/btree')
-rw-r--r-- | src/main/java/io/trygvis/btree/HeapFile.java | 7 | ||||
-rw-r--r-- | src/main/java/io/trygvis/btree/HeapPage.java | 17 |
2 files changed, 19 insertions, 5 deletions
diff --git a/src/main/java/io/trygvis/btree/HeapFile.java b/src/main/java/io/trygvis/btree/HeapFile.java index 7a960c8..6bd0451 100644 --- a/src/main/java/io/trygvis/btree/HeapFile.java +++ b/src/main/java/io/trygvis/btree/HeapFile.java @@ -37,15 +37,18 @@ public class HeapFile implements Closeable { return HeapPage.heapPageFromBytes(page, buffer); } - public void writePage(HeapPage page) throws IOException { + public long writePage(HeapPage page) throws IOException { long position; if (page.pageNumber == -1) { - position = file.length(); + 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 { diff --git a/src/main/java/io/trygvis/btree/HeapPage.java b/src/main/java/io/trygvis/btree/HeapPage.java index 499a244..a931260 100644 --- a/src/main/java/io/trygvis/btree/HeapPage.java +++ b/src/main/java/io/trygvis/btree/HeapPage.java @@ -22,7 +22,12 @@ public class HeapPage { } public static HeapPage heapPageFromBytes(int pageNumber, ByteBuffer bytes) { - int freePosition = bytes.getInt(); + int freePosition = bytes.getInt(FREE_POSITION_INDEX); + + if (freePosition > bytes.capacity() || freePosition < headerSize) { + throw new RuntimeException("Invalid free position: " + freePosition); + } + return new HeapPage(pageNumber, bytes, freePosition); } @@ -31,8 +36,6 @@ public class HeapPage { } public void append(byte[] item) { -// System.out.println("io.trygvis.btree.HeapPage.append"); - int bytesFree = bytesFree(); int bytesRequested = item.length; @@ -58,6 +61,8 @@ public class HeapPage { return new Iterable<ByteBuffer>() { @Override public Iterator<ByteBuffer> iterator() { + System.out.println("io.trygvis.btree.HeapPage.iterator"); + return new Iterator<ByteBuffer>() { private int position; @@ -65,21 +70,27 @@ public class HeapPage { { position = bytes.capacity(); + System.out.println("position = " + position); next = findNext(); } private ByteBuffer findNext() { + System.out.println("io.trygvis.btree.HeapPage.findNext"); if (position == headerSize) { + System.out.println("at end"); return null; } int size = bytes.getInt(position - itemSize); if (size == 0) { + System.out.println("at end"); return null; } position -= itemSize + size; + + System.out.println("item: size: " + size + ", new position: " + position); ByteBuffer copy = bytes.duplicate(); copy.position(position); copy.limit(position + size); |