Skip to content

Commit

Permalink
feat: add more multi page tests (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevmo314 authored Jan 6, 2024
1 parent c853c3b commit bd764fa
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 2 deletions.
11 changes: 10 additions & 1 deletion pkg/btree/multi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package btree

import (
"encoding/binary"
"errors"
"io"
)

Expand Down Expand Up @@ -55,12 +56,20 @@ func (m *LinkedMetaPage) Next() (*LinkedMetaPage, error) {
}

func (m *LinkedMetaPage) AddNext() (*LinkedMetaPage, error) {
// check that the next pointer is zero
curr, err := m.Next()
if err != nil {
return nil, err
}
if curr != nil {
return nil, errors.New("next pointer is not zero")
}
offset, err := m.rws.Seek(0, io.SeekEnd)
if err != nil {
return nil, err
}
next := &LinkedMetaPage{rws: m.rws, offset: uint64(offset)}
if err := binary.Write(m.rws, binary.LittleEndian, next.offset); err != nil {
if err := next.Reset(); err != nil {
return nil, err
}
// save the next pointer
Expand Down
64 changes: 63 additions & 1 deletion pkg/btree/multi_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package btree

import "testing"
import (
"reflect"
"testing"
)

func TestMultiBPTree(t *testing.T) {
t.Run("empty tree", func(t *testing.T) {
Expand Down Expand Up @@ -36,4 +39,63 @@ func TestMultiBPTree(t *testing.T) {
t.Fatalf("expected length 36, got %d", mp.Length)
}
})

t.Run("insert a second page", func(t *testing.T) {
b := newSeekableBuffer()
tree := NewMultiBPTree(b)
if err := tree.Reset(); err != nil {
t.Fatal(err)
}
next1, err := tree.AddNext()
if err != nil {
t.Fatal(err)
}
if next1.MemoryPointer().Offset != 36 {
t.Fatalf("expected offset 36, got %d", next1)
}
if next1.MemoryPointer().Length != 36 {
t.Fatalf("expected length 36, got %d", next1)
}
next2, err := next1.AddNext()
if err != nil {
t.Fatal(err)
}
if next2.MemoryPointer().Offset != 72 {
t.Fatalf("expected offset 72, got %d", next2)
}
if next2.MemoryPointer().Length != 36 {
t.Fatalf("expected length 36, got %d", next2)
}

// check the first page
m1, err := tree.Next()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(m1.MemoryPointer(), next1.MemoryPointer()) {
t.Fatalf("got %v want %v", m1.MemoryPointer(), next1.MemoryPointer())
}
})

t.Run("duplicate next pointer", func(t *testing.T) {
b := newSeekableBuffer()
tree := NewMultiBPTree(b)
if err := tree.Reset(); err != nil {
t.Fatal(err)
}
next1, err := tree.AddNext()
if err != nil {
t.Fatal(err)
}
if next1.MemoryPointer().Offset != 36 {
t.Fatalf("expected offset 36, got %d", next1)
}
if next1.MemoryPointer().Length != 36 {
t.Fatalf("expected length 36, got %d", next1)
}
_, err = tree.AddNext()
if err == nil {
t.Fatal("expected error")
}
})
}

0 comments on commit bd764fa

Please sign in to comment.