-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtree.go
335 lines (286 loc) · 6.13 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
package muxter
import (
"errors"
"fmt"
"regexp"
"strings"
"github.com/davidmdm/muxter/internal"
)
const (
static = iota
wildcard
expression
catchall
)
var errMultipleRegistrations = errors.New("multiple registrations")
type value struct {
handler Handler
pattern string
isRedirect bool
}
type node struct {
Value *value
Wildcard *node
Catchall *node
Expression *node
Key string
Children []*node
Indices []byte
Type int
expression *regexp.Regexp
}
func (n *node) Insert(key string, value *value) error {
idx := strings.IndexAny(key, "#:*")
if idx == -1 {
_, err := n.insert(key, value)
return err
}
pre := key[:idx]
n, err := n.insert(pre, nil)
if err != nil {
return err
}
post := key[idx:]
slashIdx := func() int {
if post[0] != '#' {
return strings.IndexByte(post, '/')
}
i := regexp.MustCompile(`[^\\]/`).FindStringIndex(post)
if i == nil {
return -1
}
return i[1] - 1
}()
if slashIdx == -1 {
_, err := n.insert(post, value)
return err
}
if post[0] == '*' {
return fmt.Errorf("cannot register segments after a catchall expression %q", post[:slashIdx])
}
n, err = n.insert(post[:slashIdx], nil)
if err != nil {
return err
}
return n.Insert(post[slashIdx:], value)
}
func (n *node) insert(key string, value *value) (*node, error) {
switch key[0] {
case '#':
idx := strings.IndexByte(key, ':')
if idx == -1 {
return nil, fmt.Errorf("invalid regexp param: %s", key)
}
k := key[1:idx]
exp, err := regexp.Compile(fmt.Sprintf("^(%s)", key[idx+1:]))
if err != nil {
return nil, err
}
if n.Expression != nil {
oldCanonicalKey := fmt.Sprintf("#%s:%s", n.Expression.Key, n.Expression.expression)
newCanonicalKey := fmt.Sprintf("#%s:%s", k, exp)
if oldCanonicalKey != newCanonicalKey {
return nil, fmt.Errorf("mismatched regexp segments %s and %s", oldCanonicalKey, newCanonicalKey)
}
if value != nil {
if n.Expression.Value != nil {
return nil, errMultipleRegistrations
}
n.Expression.Value = value
}
return n.Expression, nil
}
n.Expression = &node{
Value: value,
Key: k,
Type: expression,
expression: exp,
}
return n.Expression, nil
case ':':
if n.Wildcard != nil {
if n.Wildcard.Key != key[1:] {
return nil, fmt.Errorf("mismatched wild cards :%s and %s", n.Wildcard.Key, key)
}
if value != nil {
if n.Wildcard.Value != nil {
return nil, errMultipleRegistrations
}
n.Wildcard.Value = value
}
return n.Wildcard, nil
}
n.Wildcard = &node{
Key: key[1:],
Value: value,
Type: wildcard,
}
return n.Wildcard, nil
case '*':
if n.Catchall != nil {
if n.Catchall.Key != key[1:] {
return nil, fmt.Errorf("mismatched wild cards *%s and %s", n.Catchall.Key, key)
}
return nil, errMultipleRegistrations
}
n.Catchall = &node{
Key: key[1:],
Value: value,
Type: catchall,
}
return n.Catchall, nil
}
for i, childNode := range n.Children {
if key == childNode.Key {
if value != nil {
if childNode.Value != nil {
return nil, errMultipleRegistrations
}
childNode.Value = value
}
return childNode, nil
}
cp := commonPrefixLength(childNode.Key, key)
if cp == 0 {
continue
}
if cp == len(childNode.Key) {
return childNode.insert(key[cp:], value)
}
childNode.Key = childNode.Key[cp:]
if cp == len(key) {
n.Children[i] = &node{
Key: key,
Children: []*node{childNode},
Indices: []byte{childNode.Key[0]},
Value: value,
}
return n.Children[i], nil
}
targetNode := &node{
Key: key[cp:],
Children: []*node{},
Value: value,
}
n.Children[i] = &node{
Key: key[:cp],
Children: []*node{childNode, targetNode},
Indices: []byte{childNode.Key[0], targetNode.Key[0]},
}
return targetNode, nil
}
targetNode := &node{
Key: key,
Children: []*node{},
Value: value,
}
n.Children = append(n.Children, targetNode)
n.Indices = append(n.Indices, targetNode.Key[0])
return targetNode, nil
}
func (n *node) Lookup(path string, params *[]internal.Param, matchTrailingSlash bool) (result *value) {
var fallback *value
defer func() {
if result == nil {
result = fallback
}
}()
var wildcardbackup *node
Walk:
for {
switch n.Type {
case static:
if !strings.HasPrefix(path, n.Key) {
if wildcardbackup != nil {
n = wildcardbackup
continue Walk
}
if n.Value != nil && path+"/" == n.Key {
return &value{isRedirect: true, pattern: n.Value.pattern[:len(n.Value.pattern)-1]}
}
return nil
}
path = path[len(n.Key):]
if path == "" {
return n.Value
}
if n.IsSubdirNode() {
fallback = n.Value
}
case wildcard:
if idx := strings.IndexByte(path, '/'); idx == -1 {
*params = append(*params, internal.Param{
Key: n.Key,
Value: path,
})
return n.Value
} else {
*params = append(*params, internal.Param{
Key: n.Key,
Value: path[:idx],
})
path = path[idx:]
}
case catchall:
*params = append(*params, internal.Param{
Key: n.Key,
Value: path,
})
return n.Value
case expression:
i := n.expression.FindStringIndex(path)
if i == nil {
return nil
}
*params = append(*params, internal.Param{
Key: n.Key,
Value: path[:i[1]],
})
path = path[i[1]:]
if len(path) == 0 {
return n.Value
}
}
if matchTrailingSlash && path == "/" && n.Value != nil {
fallback = n.Value
}
wildcardbackup = n.Wildcard
targetIndice := path[0]
for i, c := range n.Indices {
if c == targetIndice {
n = n.Children[i]
continue Walk
}
}
if n.Catchall != nil {
n = n.Catchall
continue Walk
}
if n.Wildcard != nil {
n = n.Wildcard
continue Walk
}
if n.Expression != nil {
n = n.Expression
continue Walk
}
return nil
}
}
func (node *node) IsSubdirNode() bool {
return node != nil && node.Value != nil && strings.HasSuffix(node.Key, "/")
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func commonPrefixLength(a, b string) (i int) {
for ; i < min(len(a), len(b)); i++ {
if a[i] != b[i] {
break
}
}
return
}