tree.go raw

   1  package lattice
   2  
   3  import "fmt"
   4  
   5  // Tree is one lattice: eight branch roots, a node pool, a record pool, a free
   6  // list of nodes and the expansion journal. It is either fully in memory
   7  // (Store == nil) or backed by an .iskr file through a Store.
   8  type Tree struct {
   9  	Roots     [C]uint32
  10  	FreeHead  uint32
  11  	FreeCount uint32
  12  	nCount    uint32 // nodes in use, including free-list nodes
  13  	rCount    uint32 // records allocated
  14  	Pending   []PendingExp
  15  	RecKey    map[uint32]Key // record index -> key; keys are not stored on disk
  16  	Store     *Store
  17  
  18  	// In-memory pools, used only when Store == nil.
  19  	Nodes      []Node
  20  	Records    []Record
  21  	Meta       []MetaEntry // go-ref second layer, in-memory trees only
  22  	Lex        []LexEntry
  23  	StringPool []byte
  24  	Adj        []AdjLink
  25  
  26  	KeyMeta map[Key][2]uint32 // MESH key map, in-memory trees only
  27  	MetaLen uint32            // MESH header value for len(Meta) at save time
  28  	LexLen  uint32
  29  
  30  	pendingAdj map[uint32][]uint32
  31  
  32  	SkipRecKey bool
  33  
  34  	// ClampedBlocks counts blocks whose key count exceeded C and was read as C
  35  	// to keep the index arithmetic in range. It is diagnostic only.
  36  	ClampedBlocks uint64
  37  
  38  	// fileBytes is the size of the backing file, recorded at open and after
  39  	// every flush.
  40  	fileBytes int64
  41  
  42  	// SourceVersion is the format version this tree was read from. It is always
  43  	// Version for a tree in memory: ReadV4File is the only path that produces a
  44  	// version-4 in-memory tree, and its output is written as version 5.
  45  	SourceVersion uint16
  46  }
  47  
  48  // NewTree returns an empty in-memory tree with one empty root per branch.
  49  func NewTree(capacity int) *Tree {
  50  	if capacity < C {
  51  		capacity = C
  52  	}
  53  	t := &Tree{
  54  		FreeHead: NullIndex,
  55  		nCount:   C,
  56  		RecKey:   make(map[uint32]Key),
  57  		Nodes:    make([]Node, C, capacity),
  58  	}
  59  	for i := 0; i < C; i++ {
  60  		t.Roots[i] = uint32(i)
  61  		initNodeChildren(&t.Nodes[i])
  62  		t.Nodes[i].SetBranch(Branch(i))
  63  		t.Nodes[i].Mult = 1
  64  	}
  65  	return t
  66  }
  67  
  68  // AllocTree builds a tree over pre-allocated pools, for deserialisation.
  69  func AllocTree(nCount, rCount uint32, roots [C]uint32) *Tree {
  70  	return &Tree{
  71  		Nodes:    make([]Node, nCount),
  72  		Records:  make([]Record, rCount),
  73  		FreeHead: NullIndex,
  74  		nCount:   nCount,
  75  		rCount:   rCount,
  76  		RecKey:   make(map[uint32]Key),
  77  		Roots:    roots,
  78  	}
  79  }
  80  
  81  // NodeCount is the number of nodes in use, including free-list nodes.
  82  func (t *Tree) NodeCount() uint32 { return t.nCount }
  83  
  84  // RecordCount is the number of records allocated.
  85  func (t *Tree) RecordCount() uint32 { return t.rCount }
  86  
  87  // RootIdx returns the root node index of a branch.
  88  func (t *Tree) RootIdx(b Branch) uint32 { return t.Roots[b] }
  89  
  90  // IsMemory reports whether the tree has no file backing.
  91  func (t *Tree) IsMemory() bool { return t.Store == nil }
  92  
  93  // GetNode returns the node at idx. The pointer stays valid until the next
  94  // allocation, Flush or Compact; callers re-fetch after allocating, as the moxie
  95  // source does after every page-cache miss.
  96  func (t *Tree) GetNode(idx uint32) (*Node, error) {
  97  	if t.Store != nil {
  98  		return t.Store.node(idx)
  99  	}
 100  	if idx >= uint32(len(t.Nodes)) {
 101  		return nil, fmt.Errorf("lattice: node %d out of range (have %d)", idx, len(t.Nodes))
 102  	}
 103  	return &t.Nodes[idx], nil
 104  }
 105  
 106  // GetRecord returns the record at idx.
 107  func (t *Tree) GetRecord(idx uint32) (*Record, error) {
 108  	if t.Store != nil {
 109  		return t.Store.record(idx)
 110  	}
 111  	if idx >= uint32(len(t.Records)) {
 112  		return nil, fmt.Errorf("lattice: record %d out of range (have %d)", idx, len(t.Records))
 113  	}
 114  	return &t.Records[idx], nil
 115  }
 116  
 117  // MustNode is GetNode for an index already known good. A corrupt index panics
 118  // rather than returning an empty node.
 119  func (t *Tree) MustNode(idx uint32) *Node {
 120  	n, err := t.GetNode(idx)
 121  	if err != nil {
 122  		panic(err.Error())
 123  	}
 124  	return n
 125  }
 126  
 127  // MustRecord is the Record counterpart of MustNode.
 128  func (t *Tree) MustRecord(idx uint32) *Record {
 129  	r, err := t.GetRecord(idx)
 130  	if err != nil {
 131  		panic(err.Error())
 132  	}
 133  	return r
 134  }
 135  
 136  func (t *Tree) allocNode() uint32 {
 137  	if t.FreeHead != NullIndex {
 138  		idx := t.FreeHead
 139  		node := t.MustNode(idx)
 140  		t.FreeHead = node.Children[0]
 141  		t.FreeCount--
 142  		*node = Node{}
 143  		initNodeChildren(node)
 144  		t.markNodeDirty(idx)
 145  		return idx
 146  	}
 147  	if t.Store != nil {
 148  		return t.Store.allocNode(&t.nCount)
 149  	}
 150  	idx := t.nCount
 151  	t.nCount++
 152  	if int(idx) < len(t.Nodes) {
 153  		t.Nodes[idx] = Node{}
 154  		initNodeChildren(&t.Nodes[idx])
 155  		return idx
 156  	}
 157  	var n Node
 158  	initNodeChildren(&n)
 159  	t.Nodes = append(t.Nodes, n)
 160  	return idx
 161  }
 162  
 163  func (t *Tree) allocRecord() uint32 {
 164  	if t.Store != nil {
 165  		return t.Store.allocRecord(&t.rCount)
 166  	}
 167  	idx := t.rCount
 168  	t.rCount++
 169  	if int(idx) < len(t.Records) {
 170  		t.Records[idx] = Record{}
 171  		t.Records[idx].Link[0] = NullRec
 172  		t.Records[idx].Link[1] = NullRec
 173  		return idx
 174  	}
 175  	t.Records = append(t.Records, Record{})
 176  	t.Records[idx].Link[0] = NullRec
 177  	t.Records[idx].Link[1] = NullRec
 178  	return idx
 179  }
 180  
 181  func (t *Tree) markNodeDirty(idx uint32) {
 182  	if t.Store != nil {
 183  		t.Store.markNodeDirty(idx)
 184  	}
 185  }
 186  
 187  func (t *Tree) markRecDirty(idx uint32) {
 188  	if t.Store != nil {
 189  		t.Store.markRecDirty(idx)
 190  	}
 191  }
 192  
 193  // Flush writes pending pages, then the header. No-op in memory.
 194  func (t *Tree) Flush() error {
 195  	if t.Store == nil {
 196  		return nil
 197  	}
 198  	return t.Store.Flush(t)
 199  }
 200  
 201  // Close flushes and releases the file. No-op in memory.
 202  func (t *Tree) Close() error {
 203  	if t.Store == nil {
 204  		return nil
 205  	}
 206  	return t.Store.Close(t)
 207  }
 208  
 209  // rebuildRecKey rebuilds record index -> key from every walk that reaches a
 210  // key slot: the eight roots and every record pointer. A block with a key count
 211  // of zero is a child, which is file data, so no record pointer can name it; the
 212  // same holds for a pointer at or beyond the record count. Both are skipped, and
 213  // the skip is counted rather than followed.
 214  func (t *Tree) rebuildRecKey() {
 215  	t.RecKey = make(map[uint32]Key)
 216  	queue := make([]uint32, 0, C)
 217  	for b := 0; b < C; b++ {
 218  		queue = append(queue, t.Roots[b])
 219  	}
 220  	seen := make(map[uint32]struct{}, t.nCount)
 221  	for len(queue) > 0 {
 222  		idx := queue[len(queue)-1]
 223  		queue = queue[:len(queue)-1]
 224  		if idx == NullIndex || idx >= t.nCount {
 225  			continue
 226  		}
 227  		if _, done := seen[idx]; done {
 228  			continue
 229  		}
 230  		seen[idx] = struct{}{}
 231  		node := t.MustNode(idx)
 232  		k := node.KeyCount()
 233  		if k > C {
 234  			t.ClampedBlocks++
 235  			k = C
 236  		}
 237  		for i := 0; i < k; i++ {
 238  			ri := node.RecPtrs[i]
 239  			if ri == NullRec || ri >= t.rCount {
 240  				continue
 241  			}
 242  			t.RecKey[ri] = node.Keys[i]
 243  			queue = append(queue, ri)
 244  		}
 245  		for i := 0; i <= k; i++ {
 246  			if node.Children[i] != NullIndex {
 247  				queue = append(queue, node.Children[i])
 248  			}
 249  		}
 250  	}
 251  }
 252  
 253  // DumpNode prints one node.
 254  func (t *Tree) DumpNode(idx uint32) {
 255  	n := t.MustNode(idx)
 256  	fmt.Printf("node[%d] keys=%d branch=%d leaf=%v children=[%x,%x,%x,%x,%x] rec=[%x,%x,%x,%x]\n",
 257  		idx, n.KeyCount(), n.GetBranch(), n.IsLeaf(),
 258  		n.Children[0], n.Children[1], n.Children[2], n.Children[3], n.Children[4],
 259  		n.RecPtrs[0], n.RecPtrs[1], n.RecPtrs[2], n.RecPtrs[3])
 260  }
 261