/
node.go
59 lines (52 loc) · 1.4 KB
/
node.go
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
package trog
type rawNode struct {
Id NodeId
Pairs []Pair // Sorted pair of key/value pairs
Flags []string // Sorted list of flags
ParentIds []NodeId // Every ancestor id, all the way up to the root
ChildIds []NodeId // Every direct child id of this node
}
type Node struct {
Pairs PairMap // Key/value pairs
Flags FlagMap // Value-only flags
Parent *Node // Direct ancestor of this node
Children []*Node // Direct children of this node
Parents []*Node // Every ancestor, all the way up to the root
}
// Create a new, empty, node.
func NewNode() *Node {
return &Node{
Pairs: make(PairMap),
Flags: make(FlagMap),
}
}
// Add a new node between the given node and its parent.
func (node *Node) Split() *Node {
newNode := NewNode()
parent := node.Parent
if parent != nil {
parent.delChild(node)
parent.addChild(newNode)
}
newNode.addChild(node)
return newNode
}
// Add a new child to the given node.
func (node *Node) AddChild() *Node {
newNode := NewNode()
node.addChild(newNode)
return newNode
}
func (node *Node) addChild(child *Node) {
child.Parent = node
node.Children = append(node.Children, child)
}
func (node *Node) delChild(child *Node) {
for i := 0; i < len(node.Children); i++ {
if node.Children[i] == child {
node.Children[i] = node.Children[len(node.Children)-1]
node.Children = node.Children[:len(node.Children)-1]
child.Parent = nil
}
}
}