package lattice import "fmt" // Tree is one lattice: eight branch roots, a node pool, a record pool, a free // list of nodes and the expansion journal. It is either fully in memory // (Store == nil) or backed by an .iskr file through a Store. type Tree struct { Roots [C]uint32 FreeHead uint32 FreeCount uint32 nCount uint32 // nodes in use, including free-list nodes rCount uint32 // records allocated Pending []PendingExp RecKey map[uint32]Key // record index -> key; keys are not stored on disk Store *Store // In-memory pools, used only when Store == nil. Nodes []Node Records []Record Meta []MetaEntry // go-ref second layer, in-memory trees only Lex []LexEntry StringPool []byte Adj []AdjLink KeyMeta map[Key][2]uint32 // MESH key map, in-memory trees only MetaLen uint32 // MESH header value for len(Meta) at save time LexLen uint32 pendingAdj map[uint32][]uint32 SkipRecKey bool // ClampedBlocks counts blocks whose key count exceeded C and was read as C // to keep the index arithmetic in range. It is diagnostic only. ClampedBlocks uint64 // fileBytes is the size of the backing file, recorded at open and after // every flush. fileBytes int64 // SourceVersion is the format version this tree was read from. It is always // Version for a tree in memory: ReadV4File is the only path that produces a // version-4 in-memory tree, and its output is written as version 5. SourceVersion uint16 } // NewTree returns an empty in-memory tree with one empty root per branch. func NewTree(capacity int) *Tree { if capacity < C { capacity = C } t := &Tree{ FreeHead: NullIndex, nCount: C, RecKey: make(map[uint32]Key), Nodes: make([]Node, C, capacity), } for i := 0; i < C; i++ { t.Roots[i] = uint32(i) initNodeChildren(&t.Nodes[i]) t.Nodes[i].SetBranch(Branch(i)) t.Nodes[i].Mult = 1 } return t } // AllocTree builds a tree over pre-allocated pools, for deserialisation. func AllocTree(nCount, rCount uint32, roots [C]uint32) *Tree { return &Tree{ Nodes: make([]Node, nCount), Records: make([]Record, rCount), FreeHead: NullIndex, nCount: nCount, rCount: rCount, RecKey: make(map[uint32]Key), Roots: roots, } } // NodeCount is the number of nodes in use, including free-list nodes. func (t *Tree) NodeCount() uint32 { return t.nCount } // RecordCount is the number of records allocated. func (t *Tree) RecordCount() uint32 { return t.rCount } // RootIdx returns the root node index of a branch. func (t *Tree) RootIdx(b Branch) uint32 { return t.Roots[b] } // IsMemory reports whether the tree has no file backing. func (t *Tree) IsMemory() bool { return t.Store == nil } // GetNode returns the node at idx. The pointer stays valid until the next // allocation, Flush or Compact; callers re-fetch after allocating, as the moxie // source does after every page-cache miss. func (t *Tree) GetNode(idx uint32) (*Node, error) { if t.Store != nil { return t.Store.node(idx) } if idx >= uint32(len(t.Nodes)) { return nil, fmt.Errorf("lattice: node %d out of range (have %d)", idx, len(t.Nodes)) } return &t.Nodes[idx], nil } // GetRecord returns the record at idx. func (t *Tree) GetRecord(idx uint32) (*Record, error) { if t.Store != nil { return t.Store.record(idx) } if idx >= uint32(len(t.Records)) { return nil, fmt.Errorf("lattice: record %d out of range (have %d)", idx, len(t.Records)) } return &t.Records[idx], nil } // MustNode is GetNode for an index already known good. A corrupt index panics // rather than returning an empty node. func (t *Tree) MustNode(idx uint32) *Node { n, err := t.GetNode(idx) if err != nil { panic(err.Error()) } return n } // MustRecord is the Record counterpart of MustNode. func (t *Tree) MustRecord(idx uint32) *Record { r, err := t.GetRecord(idx) if err != nil { panic(err.Error()) } return r } func (t *Tree) allocNode() uint32 { if t.FreeHead != NullIndex { idx := t.FreeHead node := t.MustNode(idx) t.FreeHead = node.Children[0] t.FreeCount-- *node = Node{} initNodeChildren(node) t.markNodeDirty(idx) return idx } if t.Store != nil { return t.Store.allocNode(&t.nCount) } idx := t.nCount t.nCount++ if int(idx) < len(t.Nodes) { t.Nodes[idx] = Node{} initNodeChildren(&t.Nodes[idx]) return idx } var n Node initNodeChildren(&n) t.Nodes = append(t.Nodes, n) return idx } func (t *Tree) allocRecord() uint32 { if t.Store != nil { return t.Store.allocRecord(&t.rCount) } idx := t.rCount t.rCount++ if int(idx) < len(t.Records) { t.Records[idx] = Record{} t.Records[idx].Link[0] = NullRec t.Records[idx].Link[1] = NullRec return idx } t.Records = append(t.Records, Record{}) t.Records[idx].Link[0] = NullRec t.Records[idx].Link[1] = NullRec return idx } func (t *Tree) markNodeDirty(idx uint32) { if t.Store != nil { t.Store.markNodeDirty(idx) } } func (t *Tree) markRecDirty(idx uint32) { if t.Store != nil { t.Store.markRecDirty(idx) } } // Flush writes pending pages, then the header. No-op in memory. func (t *Tree) Flush() error { if t.Store == nil { return nil } return t.Store.Flush(t) } // Close flushes and releases the file. No-op in memory. func (t *Tree) Close() error { if t.Store == nil { return nil } return t.Store.Close(t) } // rebuildRecKey rebuilds record index -> key from every walk that reaches a // key slot: the eight roots and every record pointer. A block with a key count // of zero is a child, which is file data, so no record pointer can name it; the // same holds for a pointer at or beyond the record count. Both are skipped, and // the skip is counted rather than followed. func (t *Tree) rebuildRecKey() { t.RecKey = make(map[uint32]Key) queue := make([]uint32, 0, C) for b := 0; b < C; b++ { queue = append(queue, t.Roots[b]) } seen := make(map[uint32]struct{}, t.nCount) for len(queue) > 0 { idx := queue[len(queue)-1] queue = queue[:len(queue)-1] if idx == NullIndex || idx >= t.nCount { continue } if _, done := seen[idx]; done { continue } seen[idx] = struct{}{} node := t.MustNode(idx) k := node.KeyCount() if k > C { t.ClampedBlocks++ k = C } for i := 0; i < k; i++ { ri := node.RecPtrs[i] if ri == NullRec || ri >= t.rCount { continue } t.RecKey[ri] = node.Keys[i] queue = append(queue, ri) } for i := 0; i <= k; i++ { if node.Children[i] != NullIndex { queue = append(queue, node.Children[i]) } } } } // DumpNode prints one node. func (t *Tree) DumpNode(idx uint32) { n := t.MustNode(idx) fmt.Printf("node[%d] keys=%d branch=%d leaf=%v children=[%x,%x,%x,%x,%x] rec=[%x,%x,%x,%x]\n", idx, n.KeyCount(), n.GetBranch(), n.IsLeaf(), n.Children[0], n.Children[1], n.Children[2], n.Children[3], n.Children[4], n.RecPtrs[0], n.RecPtrs[1], n.RecPtrs[2], n.RecPtrs[3]) }