walk.go raw
1 package lattice
2
3 import "fmt"
4
5 // MaxTreeDepth bounds every descent. The moxie source prints FATAL and exits;
6 // this returns an error.
7 const MaxTreeDepth = 32
8
9 func errCycle(where string, branch Branch) error {
10 return fmt.Errorf("lattice: %s: B-tree cycle detected in branch %d (depth exceeded %d)", where, branch, MaxTreeDepth)
11 }
12
13 // Walk searches one branch for key. On a hit, idx is the node holding it and
14 // pos its index there. On a miss, idx is the leaf that would hold it and pos
15 // the insertion index.
16 func (t *Tree) Walk(branch Branch, key Key) (idx uint32, pos int, found bool, err error) {
17 i := t.Roots[branch]
18 for depth := 0; depth < MaxTreeDepth; depth++ {
19 node, e := t.GetNode(i)
20 if e != nil {
21 return 0, 0, false, e
22 }
23 k := node.KeyCount()
24 p := 0
25 for p < k && node.Keys[p] < key {
26 p++
27 }
28 if p < k && node.Keys[p] == key {
29 return i, p, true, nil
30 }
31 if node.IsLeaf() {
32 return i, p, false, nil
33 }
34 child := node.Children[p]
35 if child == NullIndex {
36 return i, p, false, nil
37 }
38 i = child
39 }
40 return 0, 0, false, errCycle("Walk", branch)
41 }
42
43 // WalkPath returns the node indices from root to the node holding key, or nil
44 // if the key is absent.
45 func (t *Tree) WalkPath(branch Branch, key Key) ([]uint32, error) {
46 path := make([]uint32, 0, 8)
47 i := t.Roots[branch]
48 for depth := 0; depth < MaxTreeDepth; depth++ {
49 path = append(path, i)
50 node, e := t.GetNode(i)
51 if e != nil {
52 return nil, e
53 }
54 k := node.KeyCount()
55 p := 0
56 for p < k && node.Keys[p] < key {
57 p++
58 }
59 if p < k && node.Keys[p] == key {
60 return path, nil
61 }
62 if node.IsLeaf() {
63 return nil, nil
64 }
65 child := node.Children[p]
66 if child == NullIndex {
67 return nil, nil
68 }
69 i = child
70 }
71 return nil, errCycle("WalkPath", branch)
72 }
73
74 // Lookup returns the record for key in branch, or nil if the key is absent.
75 func (t *Tree) Lookup(branch Branch, key Key) (*Record, error) {
76 idx, pos, found, err := t.Walk(branch, key)
77 if err != nil || !found {
78 return nil, err
79 }
80 recIdx := t.MustNode(idx).RecPtrs[pos]
81 if recIdx == NullRec {
82 return nil, nil
83 }
84 return t.GetRecord(recIdx)
85 }
86
87 // LookupRecIdx returns the record index for key in branch, or NullRec.
88 func (t *Tree) LookupRecIdx(branch Branch, key Key) (uint32, error) {
89 idx, pos, found, err := t.Walk(branch, key)
90 if err != nil || !found {
91 return NullRec, err
92 }
93 return t.MustNode(idx).RecPtrs[pos], nil
94 }
95
96 // RecordKey returns the key registered for a record index.
97 func (t *Tree) RecordKey(recIdx uint32) (Key, bool) {
98 k, ok := t.RecKey[recIdx]
99 return k, ok
100 }
101