package lattice import ( "sort" ) // Entry is a key paired with its record index, the shape bulk operations and // the walker use. iskra/canonical.mx calls this BulkEntry. type Entry struct { Key Key RecIdx uint32 } // BranchEntries returns every live key in one branch, in ascending key order. func (t *Tree) BranchEntries(branch Branch) ([]Entry, error) { var out []Entry var walk func(idx uint32) error walk = func(idx uint32) error { node, err := t.GetNode(idx) if err != nil { return err } k := node.KeyCount() for i := 0; i < k; i++ { if !node.IsLeaf() { if err := walk(node.Children[i]); err != nil { return err } } if node.RecPtrs[i] != NullRec { out = append(out, Entry{Key: node.Keys[i], RecIdx: node.RecPtrs[i]}) } } if !node.IsLeaf() { return walk(node.Children[k]) } return nil } if err := walk(t.Roots[branch]); err != nil { return nil, err } return out, nil } // Entries returns every live key across all branches, branch by branch, in // ascending key order within each branch. func (t *Tree) Entries() ([]Entry, error) { var all []Entry for b := 0; b < C; b++ { e, err := t.BranchEntries(Branch(b)) if err != nil { return nil, err } all = append(all, e...) } return all, nil } // SortEntries sorts entries by key ascending. func SortEntries(entries []Entry) { sort.Slice(entries, func(i, j int) bool { return entries[i].Key < entries[j].Key }) } // Depth returns the depth of the tree hanging off rootIdx, in nodes, with an // empty tree at 0 and a single leaf at 1. The moxie canonical.mx estimates // depth from node count instead; this walks it. func (t *Tree) Depth(rootIdx uint32) (int, error) { node, err := t.GetNode(rootIdx) if err != nil { return 0, err } if node.KeyCount() == 0 { return 0, nil } if node.IsLeaf() { return 1, nil } d, err := t.Depth(node.Children[0]) if err != nil { return 0, err } return 1 + d, nil }