-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtree.go
397 lines (384 loc) · 8.73 KB
/
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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package radix
import (
"bytes"
"strings"
"sync"
"github.com/gbrlsnchs/color"
)
const (
// Tsafe activates thread safety.
Tsafe = 1 << iota
// Tdebug adds more information to the tree's string representation.
Tdebug
// Tbinary uses a binary PATRICIA tree instead of a prefix tree.
Tbinary
// Tnocolor disables colorful output.
Tnocolor
)
// Tree is a radix tree.
type Tree struct {
root *Node
length int // total number of nodes
size int // total byte size
safe bool
binary bool
placeholder byte
delim byte
mu *sync.RWMutex
bd *builder
}
// New creates a named radix tree with a single node (its root).
func New(flags int) *Tree {
tr := &Tree{
root: &Node{},
length: 1,
}
if flags&Tbinary > 0 {
tr.binary = true
tr.root.edges = make([]*edge, 2) // create two empty edges
}
if flags&Tsafe > 0 {
tr.mu = &sync.RWMutex{}
tr.safe = true
}
tr.bd = &builder{
Builder: &strings.Builder{},
debug: flags&Tdebug > 0,
}
tr.bd.colors[colorRed] = color.New(color.CodeFgRed)
tr.bd.colors[colorGreen] = color.New(color.CodeFgGreen)
tr.bd.colors[colorMagenta] = color.New(color.CodeFgMagenta)
tr.bd.colors[colorBold] = color.New(color.CodeBold)
for _, c := range tr.bd.colors {
c.SetDisabled(flags&Tnocolor > 0)
}
return tr
}
// Add adds a new node to the tree.
func (tr *Tree) Add(label string, v interface{}) {
// No empty strings or interfaces allowed.
if label == "" || v == nil {
return
}
if tr.safe {
defer tr.mu.Unlock()
tr.mu.Lock()
}
tnode := tr.root
if tr.binary {
nn := tnode.addBinary(label, v)
tr.length += nn
tr.size += nn / 8
return
}
for {
var next *edge
var slice string
for _, edge := range tnode.edges {
var found int
slice = edge.label
for i := range slice {
if i < len(label) && slice[i] == label[i] {
found++
continue
}
break
}
if found > 0 {
label = label[found:]
slice = slice[found:]
next = edge
break
}
}
if next != nil {
tnode = next.n
tnode.priority++
// Match the whole word.
if len(label) == 0 {
// The label is exactly the same as the edge's label,
// so just replace its node's value.
//
// Example:
// (root) -> tnode("tomato", v1)
// becomes
// (root) -> tnode("tomato", v2)
if len(slice) == 0 {
tnode.Value = v
return
}
// The label is a prefix of the edge's label.
//
// Example:
// (root) -> tnode("tomato", v1)
// then add "tom"
// (root) -> ("tom", v2) -> ("ato", v1)
next.label = next.label[:len(next.label)-len(slice)]
c := tnode.clone()
c.priority--
tnode.edges = []*edge{
&edge{
label: slice,
n: c,
},
}
tnode.Value = v
tr.length++
return
}
// Add a new node but break its parent into prefix and
// the remaining slice as a new edge.
//
// Example:
// (root) -> ("tomato", v1)
// then add "tornado"
// (root) -> ("to", nil) -> ("mato", v1)
// +> ("rnado", v2)
if len(slice) > 0 {
c := tnode.clone()
c.priority--
tnode.edges = []*edge{
&edge{ // the suffix that is clone into a new node
label: slice,
n: c,
},
&edge{ // the new node
label: label,
n: &Node{
Value: v,
depth: tnode.depth + 1,
priority: 1,
},
},
}
next.label = next.label[:len(next.label)-len(slice)]
tnode.Value = nil
tr.length += 2
tr.size += len(label)
return
}
continue
}
tnode.edges = append(tnode.edges, &edge{
label: label,
n: &Node{
Value: v,
depth: tnode.depth + 1,
priority: 1,
},
})
tr.length++
tr.size += len(label)
return
}
}
// Del deletes a node.
//
// If a parent node that holds no value ends up holding only one edge
// after a deletion of one of its edges, it gets merged with the remaining edge.
func (tr *Tree) Del(label string) {
if string(label) == "" {
return
}
if tr.safe {
defer tr.mu.Unlock()
tr.mu.Lock()
}
tnode := tr.root
if tr.binary {
del := tnode.delBinary(label)
tr.length--
bits := tr.size*8 - del
if bits == 0 {
tr.size = 0
return
}
tr.size = (bits / 8) + 1
return
}
var edgex int
var parent *edge
var ptrs []*int
for tnode != nil && label != "" {
var next *edge
// Look for exact matches.
for i, e := range tnode.edges {
if strings.HasPrefix(label, e.label) {
next = e
edgex = i
break
}
}
if next != nil {
tnode = next.n
label = label[len(next.label):]
ptrs = append(ptrs, &tnode.priority)
// While not the exact match, set the tnode's parent.
if label != "" {
parent = next
}
continue
}
// No matches.
parent = nil
tnode = nil
}
if tnode != nil {
pnode := tr.root // in case label matched in the first try
if parent != nil {
pnode = parent.n
}
// Decrement the priority of upper nodes.
done := make(chan struct{})
if tnode.Value != nil {
go func() {
for _, p := range ptrs {
*p--
}
close(done)
}()
}
// Merge tnode's edges with the parent's.
pnode.edges = append(pnode.edges, tnode.edges...)
// Remove tnode from the parent, leaving only its edges behind.
pnode.edges = append(pnode.edges[:edgex], pnode.edges[edgex+1:]...)
// When only one edge remained in pnode and its value is nil, they can be merged.
if len(pnode.edges) == 1 && pnode.Value == nil && parent != nil {
e := pnode.edges[0]
parent.label += e.label
pnode.Value = e.n.Value
pnode.edges = e.n.edges
tr.length--
}
tr.length--
if tnode.Value != nil {
<-done
}
}
}
// Get retrieves a node.
func (tr *Tree) Get(label string) (*Node, map[string]string) {
if label == "" {
return nil, nil
}
if tr.safe {
defer tr.mu.RUnlock()
tr.mu.RLock()
}
tnode := tr.root
if tr.binary {
return tnode.getBinary(label), nil
}
var params map[string]string
for tnode != nil && label != "" {
var next *edge
Walk:
for _, edge := range tnode.edges {
slice := edge.label
for {
phIndex := len(slice)
// Check if there are any placeholders.
// If there are none, then use the whole word for comparison.
if i := strings.IndexByte(slice, tr.placeholder); i >= 0 {
phIndex = i
}
prefix := slice[:phIndex]
// If "slice" (until placeholder) is not prefix of
// "label", then keep walking.
if !strings.HasPrefix(label, prefix) {
continue Walk
}
label = label[len(prefix):]
// If "slice" is the whole label,
// then the match is complete and the algorithm
// is ready to go to the next edge.
if len(prefix) == len(slice) {
next = edge
break Walk
}
// Check whether there is a delimiter.
// If there isn'tr, then use the whole world as parameter.
var delimIndex int
slice = slice[phIndex:]
if delimIndex = strings.IndexByte(slice[1:], tr.delim) + 1; delimIndex <= 0 {
delimIndex = len(slice)
}
key := slice[1:delimIndex] // remove the placeholder from the map key
slice = slice[delimIndex:]
if delimIndex = strings.IndexByte(label[1:], tr.delim) + 1; delimIndex <= 0 {
delimIndex = len(label)
}
if params == nil {
params = make(map[string]string)
}
params[key] = label[:delimIndex]
label = label[delimIndex:]
if slice == "" && label == "" {
next = edge
break Walk
}
}
}
if next != nil {
tnode = next.n
continue
}
tnode = nil
}
return tnode, params
}
// Len returns the total numbers of nodes,
// including the tree's root.
func (tr *Tree) Len() int {
if tr.safe {
defer tr.mu.RUnlock()
tr.mu.RLock()
}
return tr.length
}
// SetBoundaries sets a placeholder and a delimiter for
// the tree to be able to search for named labels.
func (tr *Tree) SetBoundaries(placeholder, delim byte) {
tr.placeholder = placeholder
tr.delim = delim
}
// Size returns the total byte size stored in the tree.
func (tr *Tree) Size() int {
return tr.size
}
// Sort sorts the tree nodes and its children recursively
// according to their priority lengther.
func (tr *Tree) Sort(st SortingTechnique) {
if !tr.binary {
if tr.safe {
defer tr.mu.Unlock()
tr.mu.Lock()
}
tr.root.sort(st)
}
}
// String returns a string representation of the tree structure.
func (tr *Tree) String() string {
if tr.safe {
defer tr.mu.RUnlock()
tr.mu.RLock()
}
bd := tr.bd
bd.Reset()
bd.WriteString(bd.colors[colorBold].Wrap("\n."))
if tr.bd.debug {
mag := bd.colors[colorMagenta]
bd.WriteString(mag.Wrapf(" (%d node", tr.length))
if tr.length != 1 {
bd.WriteString(mag.Wrap("s")) // avoid writing "1 nodes"
}
bd.WriteString(mag.Wrap(")"))
}
tr.bd.WriteByte('\n')
if tr.binary {
tr.root.writeToBinary(tr.bd, &bytes.Buffer{}, &bytes.Buffer{})
} else {
tr.root.writeTo(tr.bd)
}
return tr.bd.String()
}