Skip to content

Commit

Permalink
Add IterateKV (#265)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajeetdsouza authored Apr 15, 2021
1 parent 5946b62 commit 221ca9b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
26 changes: 26 additions & 0 deletions z/btree.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,32 @@ func (t *Tree) Iterate(fn func(node)) {
t.iterate(root, fn)
}

// IterateKV iterates through all keys and values in the tree.
// If newVal is non-zero, it will be set in the tree.
func (t *Tree) IterateKV(f func(key, val uint64) (newVal uint64)) {
t.Iterate(func(n node) {
// Only leaf nodes contain keys.
if !n.isLeaf() {
return
}

for i := 0; i < n.numKeys(); i++ {
key := n.key(i)
val := n.val(i)

// A zero value here means that this is a bogus entry.
if val == 0 {
continue
}

newVal := f(key, val)
if newVal != 0 {
n.setAt(valOffset(i), newVal)
}
}
})
}

func (t *Tree) print(n node, parentID uint64) {
n.print(parentID)
if n.isLeaf() {
Expand Down
29 changes: 29 additions & 0 deletions z/btree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,35 @@ func TestTreeCycle(t *testing.T) {
require.GreaterOrEqual(t, stats.NumPagesFree, int(float64(stats.NumPages)*0.95))
}

func TestTreeIterateKV(t *testing.T) {
bt := NewTree()

// Set entries: (i, i*10)
const n = uint64(1 << 20)
for i := uint64(1); i <= n; i++ {
bt.Set(i, i*10)
}

// Validate entries: (i, i*10)
// Set entries: (i, i*20)
count := uint64(0)
bt.IterateKV(func(k, v uint64) uint64 {
require.Equal(t, k*10, v)
count++
return k * 20
})
require.Equal(t, n, count)

// Validate entries: (i, i*20)
count = uint64(0)
bt.IterateKV(func(k, v uint64) uint64 {
require.Equal(t, k*20, v)
count++
return 0
})
require.Equal(t, n, count)
}

func TestOccupancyRatio(t *testing.T) {
// atmax 4 keys per node
setPageSize(16 * 5)
Expand Down
1 change: 0 additions & 1 deletion z/flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ func TestFlagDefault(t *testing.T) {
}

func TestGetPath(t *testing.T) {

usr, err := user.Current()
require.NoError(t, err)
homeDir := usr.HomeDir
Expand Down

0 comments on commit 221ca9b

Please sign in to comment.