forked from kenshinx/godns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sfx_tree.go
65 lines (54 loc) · 1.28 KB
/
sfx_tree.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
60
61
62
63
64
65
package main
type suffixTreeNode struct {
key string
value string
children map[string]*suffixTreeNode
}
func newSuffixTreeRoot() *suffixTreeNode {
return newSuffixTree("", "")
}
func newSuffixTree(key string, value string) *suffixTreeNode {
root := &suffixTreeNode{
key: key,
value: value,
children: map[string]*suffixTreeNode{},
}
return root
}
func (node *suffixTreeNode) ensureSubTree(key string) {
if _, ok := node.children[key]; !ok {
node.children[key] = newSuffixTree(key, "")
}
}
func (node *suffixTreeNode) insert(key string, value string) {
if c, ok := node.children[key]; ok {
c.value = value
} else {
node.children[key] = newSuffixTree(key, value)
}
}
func (node *suffixTreeNode) sinsert(keys []string, value string) {
if len(keys) == 0 {
return
}
key := keys[len(keys)-1]
if len(keys) > 1 {
node.ensureSubTree(key)
node.children[key].sinsert(keys[:len(keys)-1], value)
return
}
node.insert(key, value)
}
func (node *suffixTreeNode) search(keys []string) (string, bool) {
if len(keys) == 0 {
return "", false
}
key := keys[len(keys)-1]
if n, ok := node.children[key]; ok {
if nextValue, found := n.search(keys[:len(keys)-1]); found {
return nextValue, found
}
return n.value, (n.value != "")
}
return "", false
}