canonical.go raw

   1  package lattice
   2  
   3  import (
   4  	"sort"
   5  )
   6  
   7  // Entry is a key paired with its record index, the shape bulk operations and
   8  // the walker use. iskra/canonical.mx calls this BulkEntry.
   9  type Entry struct {
  10  	Key    Key
  11  	RecIdx uint32
  12  }
  13  
  14  // BranchEntries returns every live key in one branch, in ascending key order.
  15  func (t *Tree) BranchEntries(branch Branch) ([]Entry, error) {
  16  	var out []Entry
  17  	var walk func(idx uint32) error
  18  	walk = func(idx uint32) error {
  19  		node, err := t.GetNode(idx)
  20  		if err != nil {
  21  			return err
  22  		}
  23  		k := node.KeyCount()
  24  		for i := 0; i < k; i++ {
  25  			if !node.IsLeaf() {
  26  				if err := walk(node.Children[i]); err != nil {
  27  					return err
  28  				}
  29  			}
  30  			if node.RecPtrs[i] != NullRec {
  31  				out = append(out, Entry{Key: node.Keys[i], RecIdx: node.RecPtrs[i]})
  32  			}
  33  		}
  34  		if !node.IsLeaf() {
  35  			return walk(node.Children[k])
  36  		}
  37  		return nil
  38  	}
  39  	if err := walk(t.Roots[branch]); err != nil {
  40  		return nil, err
  41  	}
  42  	return out, nil
  43  }
  44  
  45  // Entries returns every live key across all branches, branch by branch, in
  46  // ascending key order within each branch.
  47  func (t *Tree) Entries() ([]Entry, error) {
  48  	var all []Entry
  49  	for b := 0; b < C; b++ {
  50  		e, err := t.BranchEntries(Branch(b))
  51  		if err != nil {
  52  			return nil, err
  53  		}
  54  		all = append(all, e...)
  55  	}
  56  	return all, nil
  57  }
  58  
  59  // SortEntries sorts entries by key ascending.
  60  func SortEntries(entries []Entry) {
  61  	sort.Slice(entries, func(i, j int) bool { return entries[i].Key < entries[j].Key })
  62  }
  63  
  64  // Depth returns the depth of the tree hanging off rootIdx, in nodes, with an
  65  // empty tree at 0 and a single leaf at 1. The moxie canonical.mx estimates
  66  // depth from node count instead; this walks it.
  67  func (t *Tree) Depth(rootIdx uint32) (int, error) {
  68  	node, err := t.GetNode(rootIdx)
  69  	if err != nil {
  70  		return 0, err
  71  	}
  72  	if node.KeyCount() == 0 {
  73  		return 0, nil
  74  	}
  75  	if node.IsLeaf() {
  76  		return 1, nil
  77  	}
  78  	d, err := t.Depth(node.Children[0])
  79  	if err != nil {
  80  		return 0, err
  81  	}
  82  	return 1 + d, nil
  83  }
  84