forked from sbilly/go-windivert2
/
suffixtree.go
145 lines (128 loc) · 2.2 KB
/
suffixtree.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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package utils
import (
"strings"
"sync"
)
type DomainTree struct {
*node
sep string
sync.RWMutex
}
type node struct {
value interface{}
branch map[string]*node
}
func NewDomainTree(sep string) *DomainTree {
return &DomainTree{
node: &node{
value: struct{}{},
branch: map[string]*node{},
},
sep: sep,
RWMutex: sync.RWMutex{},
}
}
func (t *DomainTree) Store(k string, v interface{}) {
t.Lock()
defer t.Unlock()
t.store(strings.Split(strings.TrimSuffix(k, t.sep), t.sep), v)
}
func (t *DomainTree) UnsafeStore(k string, v interface{}) {
t.store(strings.Split(strings.TrimSuffix(k, t.sep), t.sep), v)
}
func (n *node) store(ks []string, v interface{}) {
l := len(ks)
switch l {
case 0:
return
case 1:
k := ks[l-1]
if k == "*" || k == "**" {
n.value = v
}
b, ok := n.branch[k]
if ok {
b.value = v
return
}
n.branch[k] = &node{
value: v,
branch: map[string]*node{},
}
default:
k := ks[l-1]
b, ok := n.branch[k]
if !ok {
b = &node{
value: struct{}{},
branch: map[string]*node{},
}
n.branch[k] = b
}
b.store(ks[:l-1], v)
}
}
func (t *DomainTree) Load(k string) interface{} {
t.RLock()
defer t.RUnlock()
return t.load(strings.Split(strings.TrimSuffix(k, t.sep), t.sep))
}
func (t *DomainTree) UnsafeLoad(k string) interface{} {
return t.load(strings.Split(strings.TrimSuffix(k, t.sep), t.sep))
}
func (n *node) load(ks []string) interface{} {
l := len(ks)
switch l {
case 0:
return struct{}{}
case 1:
b, ok := n.branch[ks[l-1]]
if ok {
return b.value
}
b, ok = n.branch["*"]
if ok {
return b.value
}
b, ok = n.branch["**"]
if ok {
return b.value
}
return struct{}{}
default:
b, ok := n.branch[ks[l-1]]
if ok {
s := b.load(ks[:l-1])
if s != struct{}{} {
return s
}
}
b, ok = n.branch["*"]
if ok {
s := b.load(ks[:l-1])
if s != struct{}{} {
return s
}
}
b, ok = n.branch["**"]
if ok {
return b.value
}
return struct{}{}
}
}
func (t *DomainTree) Reset() {
t.Lock()
defer t.Unlock()
t.reset()
}
func (t *DomainTree) UnsafeReset() {
t.reset()
}
func (n *node) reset() {
n.value = nil
for k, v := range n.branch {
v.reset()
delete(n.branch, k)
}
}