-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
91 lines (76 loc) · 1.53 KB
/
node.go
File metadata and controls
91 lines (76 loc) · 1.53 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package trie
type Node struct {
// Child nodes mapped by next char in token
Children map[rune]*Node
// Stored data in node (also signifies that node is en of a token)
Buckets map[string]interface{}
// Bitmask of word length in this node and its children
Mask int
// Node depth in trie
Depth uint
}
func newNode() *Node {
return &Node{
make(map[rune]*Node),
make(map[string]interface{}),
0,
0,
}
}
func (node *Node) newChild(r rune) *Node {
n := newNode()
n.Depth = node.Depth + 1
node.Children[r] = n
return n
}
func (node *Node) insert(id string, doc interface{}, runes []rune) int {
size := uint(len(runes))
node.Mask |= 1 << size
count := 0
current := node
for _, r := range runes {
if found, ok := current.Children[r]; ok {
current = found
} else {
count += 1
current = current.newChild(r)
}
current.Mask |= 1 << size
}
current.Buckets[id] = doc
return count
}
func (node *Node) remove(id string) int {
count := 0
mask := 0
for r, child := range node.Children {
child.remove(id)
if len(child.Children) == 0 && len(child.Buckets) == 0 {
delete(node.Children, r)
count += 1
} else {
mask |= child.Mask
}
}
if _, ok := node.Buckets[id]; ok {
delete(node.Buckets, id)
}
if len(node.Buckets) != 0 {
mask |= 1 << node.Depth
}
return count
}
func (node *Node) find(runes []rune) *Node {
var ok bool
current := node
for _, r := range runes {
current, ok = current.Children[r]
if !ok {
return nil
}
}
if len(current.Buckets) == 0 {
return nil
}
return current
}