canonical.mx raw

   1  package iskra
   2  
   3  import (
   4  	"git.smesh.lol/iskradb/lattice"
   5  	"slices"
   6  )
   7  
   8  // BulkEntry represents a keyed record reference for bulk operations.
   9  // RecIdx is the record index in the iskradb tree (was MetaIdx+LexIdx pair).
  10  type BulkEntry struct {
  11  	Key    lattice.Key
  12  	RecIdx uint32
  13  }
  14  
  15  // BulkLoad is a no-op: iskradb manages its own B-tree balancing.
  16  // Kept for API compatibility.
  17  func (t *Tree) BulkLoad(entries []BulkEntry) {}
  18  
  19  // Repack is a no-op: iskradb manages its own B-tree compaction.
  20  // Kept for API compatibility.
  21  func (t *Tree) Repack() {}
  22  
  23  // ExtractEntries returns all entries in the tree across all three branches,
  24  // in ascending key order within each branch.
  25  func (t *Tree) ExtractEntries() []BulkEntry {
  26  	var entries []BulkEntry
  27  	for b := 0; b < 3; b++ {
  28  		entries = append(entries, t.extractBranchEntries(b)...)
  29  	}
  30  	return entries
  31  }
  32  
  33  func (t *Tree) extractBranchEntries(branch int) []BulkEntry {
  34  	var entries []BulkEntry
  35  	for recIdx, key := range t.db.RecKey {
  36  		if int(t.db.GetRecord(recIdx).Branch) == branch {
  37  			entries = append(entries, BulkEntry{Key: key, RecIdx: recIdx})
  38  		}
  39  	}
  40  	return entries
  41  }
  42  
  43  func SortEntries(entries []BulkEntry) {
  44  	slices.SortFunc(entries, func(a, b BulkEntry) int {
  45  		if a.Key[0] < b.Key[0] || (a.Key[0] == b.Key[0] && a.Key[1] < b.Key[1]) {
  46  			return -1
  47  		}
  48  		if a.Key[0] > b.Key[0] || (a.Key[0] == b.Key[0] && a.Key[1] > b.Key[1]) {
  49  			return 1
  50  		}
  51  		return 0
  52  	})
  53  }
  54  
  55  // Depth returns the depth of the noun branch tree (proxy for overall tree depth).
  56  func (t *Tree) Depth() int {
  57  	// Estimate depth from node count: depth ≈ log3(nodeCount)
  58  	n := t.db.NodeCount()
  59  	d := 0
  60  	for n > 1 {
  61  		n /= 3
  62  		d++
  63  	}
  64  	return d
  65  }
  66