~whereswaldon/forest-go

forest-go/grove/child-cache.go -rw-r--r-- 1.3 KiB
960be2d2Andrew Thorp 14 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package grove

import "git.sr.ht/~whereswaldon/forest-go/fields"

// ChildCache provides a simple API for keeping track of which node IDs
// are known to be children of which other node IDs.
type ChildCache struct {
	Elements map[string]map[string]*fields.QualifiedHash
}

// NewChildCache creates a new empty child cache
func NewChildCache() *ChildCache {
	return &ChildCache{
		Elements: make(map[string]map[string]*fields.QualifiedHash),
	}
}

// Add inserts the given children as child elements of the given parent.
func (c *ChildCache) Add(parent *fields.QualifiedHash, children ...*fields.QualifiedHash) {
	submap, inMap := c.Elements[parent.String()]
	if !inMap {
		submap = make(map[string]*fields.QualifiedHash)
		c.Elements[parent.String()] = submap
	}
	for _, child := range children {
		submap[child.String()] = child
	}

}

// Get returns all known children of the given parent. The second return value
// indicates whether or not the parent was found in the cache.
func (c *ChildCache) Get(parent *fields.QualifiedHash) ([]*fields.QualifiedHash, bool) {
	submap, inMap := c.Elements[parent.String()]
	if !inMap {
		return nil, false
	}
	out := make([]*fields.QualifiedHash, 0, len(submap))
	for _, child := range submap {
		out = append(out, child)
	}
	return out, true
}