Fix several bugs with opening database when the root straddles a block boundary
authorNick Downing <nick@ndcode.org>
Sun, 23 Jan 2022 06:08:37 +0000 (17:08 +1100)
committerNick Downing <nick@ndcode.org>
Sun, 23 Jan 2022 06:08:37 +0000 (17:08 +1100)
Database.mjs

index 471fe16..5697e31 100644 (file)
@@ -71,12 +71,19 @@ class Database {
             (await this.log.read(buffer, 0, count, ptr)).bytesRead === count
           )
           while (true) {
-            let i = count
-            if (i && (i = buffer.lastIndexOf(close_angle, i - 2)) != -1) {
+            let i
+            if (
+              count >= 2 &&
+                (i = buffer.lastIndexOf(close_angle, count - 2)) !== -1
+            ) {
               let eof = ptr + i + 2
               let blocks = [buffer.slice(0, i)]
+              count = i
               while (true) {
-                if (i && (i = buffer.lastIndexOf(open_angle, i - 2)) != -1) {
+                if (
+                  count >= 2 &&
+                    (i = buffer.lastIndexOf(open_angle, count - 2)) !== -1
+                ) {
                   blocks[blocks.length - 1] = blocks[blocks.length - 1].slice(i)
                   return {eof, buffer: Buffer.concat(blocks.reverse()).slice(2)}
                 }
@@ -84,12 +91,14 @@ class Database {
                 if (ptr === 0)
                   break
                 ptr -= this.block_size
+                let new_buffer = Buffer.alloc(this.block_size + 1)
                 if (count) {
-                  buffer[this.block_size] = buffer[0]
+                  new_buffer[this.block_size] = buffer[0]
                   count = this.block_size + 1
                 }
                 else
                   count = this.block_size
+                buffer = new_buffer
                 assert(
                   (await this.log.read(buffer, 0, this.block_size, ptr)).bytesRead === this.block_size
                 )