package lattice import "fmt" // MaxTreeDepth bounds every descent. The moxie source prints FATAL and exits; // this returns an error. const MaxTreeDepth = 32 func errCycle(where string, branch Branch) error { return fmt.Errorf("lattice: %s: B-tree cycle detected in branch %d (depth exceeded %d)", where, branch, MaxTreeDepth) } // Walk searches one branch for key. On a hit, idx is the node holding it and // pos its index there. On a miss, idx is the leaf that would hold it and pos // the insertion index. func (t *Tree) Walk(branch Branch, key Key) (idx uint32, pos int, found bool, err error) { i := t.Roots[branch] for depth := 0; depth < MaxTreeDepth; depth++ { node, e := t.GetNode(i) if e != nil { return 0, 0, false, e } k := node.KeyCount() p := 0 for p < k && node.Keys[p] < key { p++ } if p < k && node.Keys[p] == key { return i, p, true, nil } if node.IsLeaf() { return i, p, false, nil } child := node.Children[p] if child == NullIndex { return i, p, false, nil } i = child } return 0, 0, false, errCycle("Walk", branch) } // WalkPath returns the node indices from root to the node holding key, or nil // if the key is absent. func (t *Tree) WalkPath(branch Branch, key Key) ([]uint32, error) { path := make([]uint32, 0, 8) i := t.Roots[branch] for depth := 0; depth < MaxTreeDepth; depth++ { path = append(path, i) node, e := t.GetNode(i) if e != nil { return nil, e } k := node.KeyCount() p := 0 for p < k && node.Keys[p] < key { p++ } if p < k && node.Keys[p] == key { return path, nil } if node.IsLeaf() { return nil, nil } child := node.Children[p] if child == NullIndex { return nil, nil } i = child } return nil, errCycle("WalkPath", branch) } // Lookup returns the record for key in branch, or nil if the key is absent. func (t *Tree) Lookup(branch Branch, key Key) (*Record, error) { idx, pos, found, err := t.Walk(branch, key) if err != nil || !found { return nil, err } recIdx := t.MustNode(idx).RecPtrs[pos] if recIdx == NullRec { return nil, nil } return t.GetRecord(recIdx) } // LookupRecIdx returns the record index for key in branch, or NullRec. func (t *Tree) LookupRecIdx(branch Branch, key Key) (uint32, error) { idx, pos, found, err := t.Walk(branch, key) if err != nil || !found { return NullRec, err } return t.MustNode(idx).RecPtrs[pos], nil } // RecordKey returns the key registered for a record index. func (t *Tree) RecordKey(recIdx uint32) (Key, bool) { k, ok := t.RecKey[recIdx] return k, ok }