~whereswaldon/forest-go

forest-go/grove/child-cache.go -rw-r--r-- 1.9 KiB
e3b60d5aChris Waldon feat(grove): support removing subtrees 11 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
}

// RemoveChild removes the provided child node from the
// list of children for the provided parent node.
func (c *ChildCache) RemoveChild(parent, child *fields.QualifiedHash) error {
	submap, inMap := c.Elements[parent.String()]
	if !inMap {
		return nil
	}
	childString := child.String()
	_, contained := submap[childString]
	if !contained {
		return nil
	}
	delete(submap, childString)
	return nil
}

// RemoveParent destroys the top-level cache entry
// for the given node.
func (c *ChildCache) RemoveParent(id *fields.QualifiedHash) {
	idString := id.String()
	_, inMap := c.Elements[idString]
	if !inMap {
		return
	}
	delete(c.Elements, idString)
}