-
Notifications
You must be signed in to change notification settings - Fork 11
/
trie.go
535 lines (449 loc) · 11.8 KB
/
trie.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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
package route
import (
"bytes"
"fmt"
"net/http"
"regexp"
"strings"
"unicode"
)
// Regular expression to match url parameters
var reParam *regexp.Regexp
func init() {
reParam = regexp.MustCompile("^<([^>]+)>")
}
// Trie http://en.wikipedia.org/wiki/Trie for url matching with support of named parameters
type trie struct {
root *trieNode
// mapper takes the request and returns sequence that can be matched
mapper requestMapper
}
// Takes the expression with url and the node that corresponds to this expression and returns parsed trie
func newTrieMatcher(expression string, mapper requestMapper, result *match) (*trie, error) {
t := &trie{
mapper: mapper,
}
t.root = &trieNode{trie: t}
if len(expression) == 0 {
return nil, fmt.Errorf("empty URL expression")
}
err := t.root.parseExpression(-1, expression, result)
if err != nil {
return nil, err
}
return t, nil
}
func (t *trie) canChain(o matcher) bool {
_, ok := o.(*trie)
return ok
}
func (t *trie) chain(o matcher) (matcher, error) {
to, ok := o.(*trie)
if !ok {
return nil, fmt.Errorf("can chain only with other trie")
}
m := t.root.findMatchNode()
m.matches = nil
m.children = []*trieNode{to.root}
t.root.setLevel(-1)
return &trie{
root: t.root,
mapper: newSeqMapper(t.mapper, to.mapper),
}, nil
}
func (t *trie) String() string {
return "trieMatcher()"
}
func (t *trie) setMatch(result *match) {
t.root.setMatch(result)
}
// Tries can merge with other tries
func (t *trie) canMerge(m matcher) bool {
ot, ok := m.(*trie)
return ok && t.mapper.equivalent(ot.mapper) != nil
}
// Merge takes the other trie and modifies itself to match the passed trie as well.
// Note that trie passed as a parameter can be only simple trie without multiple branches per node, e.g. a->b->c->
// Trie on the left is "accumulating" trie that grows.
func (t *trie) merge(m matcher) (matcher, error) {
other, ok := m.(*trie)
if !ok {
return nil, fmt.Errorf("can't merge %T and %T", t, m)
}
mapper := t.mapper.equivalent(other.mapper)
if mapper == nil {
return nil, fmt.Errorf("can't merge %T and %T", t, m)
}
root, err := t.root.merge(other.root)
if err != nil {
return nil, err
}
return &trie{root: root, mapper: mapper}, nil
}
// Takes the request and returns the location if the request path matches any of its paths
// returns nil if none of the requests matches
func (t *trie) match(r *http.Request) *match {
if t.root == nil {
return nil
}
return t.root.match(t.mapper.newIter(r))
}
type trieNode struct {
trie *trie
// Matching character, can be empty in case if it's a root node
// or node with a pattern matcher
char byte
// Optional children of this node, can be empty if it's a leaf node
children []*trieNode
// If present, means that this node is a pattern matcher
patternMatcher patternMatcher
// If present it means this node contains potential match for a request, and this is a leaf node.
matches []*match
// For chained tries matching different parts of the request levels would increase for next chained trie nodes
level int
}
func (t *trieNode) setMatch(m *match) {
n := t.findMatchNode()
n.matches = []*match{m}
}
func (t *trieNode) setLevel(level int) {
if t.isRoot() {
level++
}
t.level = level
if len(t.matches) != 0 {
return
}
// Check for the match in child nodes
for _, c := range t.children {
c.setLevel(level)
}
}
func (t *trieNode) findMatchNode() *trieNode {
if len(t.matches) != 0 {
return t
}
// Check for the match in child nodes
for _, c := range t.children {
if n := c.findMatchNode(); n != nil {
return n
}
}
return nil
}
func (t *trieNode) isMatching() bool {
return len(t.matches) != 0
}
func (t *trieNode) isRoot() bool {
return t.char == byte(0) && t.patternMatcher == nil
}
func (t *trieNode) isPatternMatcher() bool {
return t.patternMatcher != nil
}
//nolint:unused
func (t *trieNode) isCharMatcher() bool {
return t.char != 0
}
func (t *trieNode) String() string {
self := ""
if t.patternMatcher != nil {
self = t.patternMatcher.String()
} else {
self = fmt.Sprintf("%c", t.char)
}
if t.isMatching() {
return fmt.Sprintf("match(%d:%s)", t.level, self)
} else if t.isRoot() {
return fmt.Sprintf("root(%d)", t.level)
} else {
return fmt.Sprintf("node(%d:%s)", t.level, self)
}
}
func (t *trieNode) equals(o *trieNode) bool {
return (t.level == o.level) && // we can merge nodes that are on the same level to avoid merges for different subtrie parts
(t.char == o.char) && // chars are equal
(t.patternMatcher == nil && o.patternMatcher == nil) || // both nodes have no matchers
((t.patternMatcher != nil && o.patternMatcher != nil) && t.patternMatcher.equals(o.patternMatcher)) // both nodes have equal matchers
}
func (t *trieNode) merge(o *trieNode) (*trieNode, error) {
children := make([]*trieNode, 0, len(t.children))
merged := make(map[*trieNode]bool)
// First, find the nodes with similar keys and merge them
for _, c := range t.children {
for _, c2 := range o.children {
// The nodes are equivalent, so we can merge them
if c.equals(c2) {
m, err := c.merge(c2)
if err != nil {
return nil, err
}
merged[c] = true
merged[c2] = true
children = append(children, m)
}
}
}
// Next, append the keys that haven't been merged
for _, c := range t.children {
if !merged[c] {
children = append(children, c)
}
}
for _, c := range o.children {
if !merged[c] {
children = append(children, c)
}
}
return &trieNode{
level: t.level,
trie: t.trie,
char: t.char,
children: children,
patternMatcher: t.patternMatcher,
matches: append(t.matches, o.matches...),
}, nil
}
func (t *trieNode) parseExpression(offset int, pattern string, m *match) error {
// We are the last element, so we are the matching node
if offset >= len(pattern)-1 {
t.matches = []*match{m}
return nil
}
// There's a next character that exists
patternMatcher, newOffset, err := parsePatternMatcher(offset+1, pattern)
// We have found the matcher, but the syntax or parameters are wrong
if err != nil {
return err
}
// Matcher was found
if patternMatcher != nil {
node := &trieNode{patternMatcher: patternMatcher, trie: t.trie}
t.children = []*trieNode{node}
return node.parseExpression(newOffset-1, pattern, m)
} else {
// Matcher was not found, next node is just a character
node := &trieNode{char: pattern[offset+1], trie: t.trie}
t.children = []*trieNode{node}
return node.parseExpression(offset+1, pattern, m)
}
}
func parsePatternMatcher(offset int, pattern string) (patternMatcher, int, error) {
if pattern[offset] != '<' {
return nil, -1, nil
}
rest := pattern[offset:]
match := reParam.FindStringSubmatchIndex(rest)
if len(match) == 0 {
return nil, -1, nil
}
// Split parsed matcher parameters separated by :
values := strings.Split(rest[match[2]:match[3]], ":")
// The common syntax is <matcherType:matcherArg1:matcherArg2>
matcherType := values[0]
matcherArgs := values[1:]
// In case if there's only one <param> is implicitly converted to <string:param>
if len(values) == 1 {
matcherType = "string"
matcherArgs = values
}
matcher, err := makeMatcher(matcherType, matcherArgs)
if err != nil {
return nil, offset, err
}
return matcher, offset + match[1], nil
}
type patternMatcher interface {
getName() string
match(i *charIter) bool
equals(other patternMatcher) bool
String() string
}
func makeMatcher(matcherType string, matcherArgs []string) (patternMatcher, error) {
switch matcherType {
case "string":
return newStringMatcher(matcherArgs)
case "path":
return newPathMatcher(matcherArgs)
case "int":
return newIntMatcher(matcherArgs)
}
return nil, fmt.Errorf("unsupported matcher: %s", matcherType)
}
func newPathMatcher(args []string) (patternMatcher, error) {
if len(args) != 1 {
return nil, fmt.Errorf("expected only one parameter - variable name, got: %s", args)
}
return &pathMatcher{name: args[0]}, nil
}
type pathMatcher struct {
name string
}
func (m *pathMatcher) String() string {
return fmt.Sprintf("<path:%s>", m.name)
}
func (m *pathMatcher) getName() string {
return m.name
}
func (m *pathMatcher) match(i *charIter) bool {
m.grabValue(i)
return true
}
func (m *pathMatcher) equals(other patternMatcher) bool {
_, ok := other.(*pathMatcher)
return ok && other.getName() == m.getName()
}
func (m *pathMatcher) grabValue(i *charIter) {
for {
_, _, ok := i.next()
if !ok {
return
}
}
}
func newStringMatcher(args []string) (patternMatcher, error) {
if len(args) != 1 {
return nil, fmt.Errorf("expected only one parameter - variable name, got: %s", args)
}
return &stringMatcher{name: args[0]}, nil
}
type stringMatcher struct {
name string
}
func (s *stringMatcher) String() string {
return fmt.Sprintf("<string:%s>", s.name)
}
func (s *stringMatcher) getName() string {
return s.name
}
func (s *stringMatcher) match(i *charIter) bool {
s.grabValue(i)
return true
}
func (s *stringMatcher) equals(other patternMatcher) bool {
_, ok := other.(*stringMatcher)
return ok && other.getName() == s.getName()
}
func (s *stringMatcher) grabValue(i *charIter) {
for {
c, sep, ok := i.next()
if !ok {
return
}
if c == sep {
i.pushBack()
return
}
}
}
func newIntMatcher(args []string) (patternMatcher, error) {
if len(args) != 1 {
return nil, fmt.Errorf("expected only one parameter - variable name, got: %s", args)
}
return &intMatcher{name: args[0]}, nil
}
type intMatcher struct {
name string
}
func (s *intMatcher) String() string {
return fmt.Sprintf("<int:%s>", s.name)
}
func (s *intMatcher) getName() string {
return s.name
}
func (s *intMatcher) match(iter *charIter) bool {
// count stores amount of consumed characters,
// so we know how many push backs to do in case there is no match
var count int
for {
c, sep, ok := iter.next()
count++
// if the current character is not a number:
// - it's either a separator that means it's a match
// - it's some other character that means it's not a match
if !unicode.IsDigit(rune(c)) {
if c == sep {
iter.pushBack()
return true
} else {
for i := 0; i < count; i++ {
iter.pushBack()
}
return false
}
}
// if it's the end of the string, it's a match
if !ok {
return true
}
}
}
func (s *intMatcher) equals(other patternMatcher) bool {
_, ok := other.(*intMatcher)
return ok && other.getName() == s.getName()
}
func (t *trieNode) matchNode(i *charIter) bool {
if i.level() != t.level {
return false
}
if t.isRoot() {
return true
}
if t.isPatternMatcher() {
return t.patternMatcher.match(i)
}
c, _, ok := i.next()
if !ok {
// we have reached the end
return false
}
if c != t.char {
// no match, so don't consume the character
i.pushBack()
return false
}
return true
}
func (t *trieNode) match(i *charIter) *match {
if !t.matchNode(i) {
return nil
}
// This is a leaf node, and we are at the last character of the pattern
if len(t.matches) != 0 && i.isEnd() {
return t.matches[0]
}
// Check for the match in child nodes
for _, c := range t.children {
p := i.position()
if match := c.match(i); match != nil {
return match
}
i.setPosition(p)
}
// Child nodes did not match and we at the boundary
if len(t.matches) != 0 && i.level() > t.level {
return t.matches[0]
}
return nil
}
// printTrie is useful for debugging and test purposes,
// it outputs the formatted representation of the trie
func printTrie(t *trie) string {
return printTrieNode(t.root)
}
func printTrieNode(e *trieNode) string {
out := &bytes.Buffer{}
printTrieNodeInner(out, e, 0)
return out.String()
}
func printTrieNodeInner(b *bytes.Buffer, e *trieNode, offset int) {
if offset == 0 {
_, _ = fmt.Fprintf(b, "\n")
}
padding := strings.Repeat(" ", offset)
_, _ = fmt.Fprintf(b, "%s%s\n", padding, e.String())
if len(e.children) != 0 {
for _, c := range e.children {
printTrieNodeInner(b, c, offset+1)
}
}
}