-
Notifications
You must be signed in to change notification settings - Fork 0
/
pattern.go
343 lines (310 loc) · 8.97 KB
/
pattern.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
package path
import (
"errors"
"fmt"
"math"
"regexp"
"strings"
"unicode"
)
const greedyPatternMaxMatchableSegments = math.MaxUint8
type segment struct {
val string
matchType MatchType
captureVarName string
captureVarPattern *regexp.Regexp
}
func (s *segment) matchUrlPathSegment(urlPath string, urlSegment *UrlSegment, caseInsensitive bool) MatchType {
matchType := s.matchType
if matchType == MatchTypeLiteral {
if int(urlSegment.endIndex-urlSegment.startIndex) == len(s.val) {
urlSegmentVal := urlPath[urlSegment.startIndex:urlSegment.endIndex]
if caseInsensitive {
if strings.EqualFold(urlSegmentVal, s.val) {
return MatchTypeLiteral
}
} else {
if urlSegmentVal == s.val {
return MatchTypeLiteral
}
}
}
return MatchTypeUnknown
} else if matchType == MatchTypeSingleSegment ||
matchType == MatchTypeCaptureVar ||
matchType == MatchTypeMultipleSegments {
return matchType
} else if matchType == MatchTypeConstraintCaptureVar {
urlSegmentVal := urlPath[urlSegment.startIndex:urlSegment.endIndex]
if s.captureVarPattern.MatchString(urlSegmentVal) {
return MatchTypeConstraintCaptureVar
}
return MatchTypeUnknown
} else if matchType == MatchTypeRegex {
urlSegmentVal := urlPath[urlSegment.startIndex:urlSegment.endIndex]
if regexSegmentMatch(urlSegmentVal, s.val, caseInsensitive) {
return MatchTypeRegex
}
return MatchTypeUnknown
}
return MatchTypeUnknown
}
func (s *segment) String() string {
return s.val
}
type Pattern struct {
caseInsensitive bool
captureVarsLen uint8
maxMatchableSegments uint8
priority uint64
segments []*segment
RawValue string
Attachment any
}
func (p *Pattern) HighPriorityThan(other *Pattern) bool {
if p.priority == other.priority {
return strings.Compare(p.RawValue, other.RawValue) < 0
}
return p.priority < other.priority
}
func (p *Pattern) isGreedy() bool {
return p.maxMatchableSegments == greedyPatternMaxMatchableSegments
}
func (p *Pattern) String() string {
return p.RawValue
}
func ParsePattern(pathPattern string, caseInsensitive bool) (*Pattern, error) {
if len(pathPattern) == 0 || pathPattern[0] != '/' {
return nil, fmt.Errorf("the path pattern should start with /")
}
if pathPattern == "/" {
return &Pattern{
caseInsensitive: caseInsensitive,
RawValue: "/",
}, nil
}
pathLen := len(pathPattern)
var maxSegmentsSize int
for pos := 0; pos < pathLen; pos++ {
if pathPattern[pos] == '/' {
maxSegmentsSize++
}
}
var pathSegmentStart int
var pathSegmentsCount uint8
var captureVarsLen uint8
var lastSegmentMatchType MatchType
var maxSegmentMatchType MatchType
segments := make([]*segment, maxSegmentsSize)
pathPatternLen := len(pathPattern)
for pos := 1; pos < pathPatternLen; pos++ {
if pathPattern[pos] == '/' || pos == pathPatternLen-1 {
var segmentVal string
if pathPattern[pos] == '/' {
segmentVal = pathPattern[pathSegmentStart+1 : pos]
} else {
segmentVal = pathPattern[pathSegmentStart+1:]
}
if err := validatePathSegment(segmentVal); err != nil {
return nil, fmt.Errorf("invalid path pattern: [%s], failed path segment validation: [%s], err: %w", pathPattern, segmentVal, err)
}
pathSegmentStart = pos
segmentMatchType := determineMatchTypeForSegment(segmentVal)
if lastSegmentMatchType == MatchTypeMultipleSegments && segmentMatchType == MatchTypeMultipleSegments {
return nil, fmt.Errorf("invalid path pattern: [%s], not allowed to have consecutive path segments with **: [%s]", pathPattern, segmentVal)
}
lastSegmentMatchType = segmentMatchType
if segmentMatchType > maxSegmentMatchType {
maxSegmentMatchType = segmentMatchType
}
segment := &segment{
val: segmentVal,
matchType: segmentMatchType,
captureVarName: "",
captureVarPattern: nil,
}
if segmentMatchType == MatchTypeCaptureVar {
captureVarsLen++
segment.captureVarName = segmentVal[1 : len(segmentVal)-1]
} else if segmentMatchType == MatchTypeConstraintCaptureVar {
captureVarsLen++
colonStartIndex := strings.IndexRune(segmentVal, ':')
regexPattern := segmentVal[colonStartIndex+1 : len(segmentVal)-1]
if caseInsensitive {
regexPattern = "(?i)" + regexPattern
}
regex, err := regexp.Compile(regexPattern)
if err != nil {
return nil, fmt.Errorf("invalid path pattern: [%s], failed to compile regex: [%s], err: %w", pathPattern, regexPattern, err)
}
segment.captureVarName = segmentVal[1:colonStartIndex]
segment.captureVarPattern = regex
}
segments[pathSegmentsCount] = segment
pathSegmentsCount++
}
}
maxMatchableSegments := pathSegmentsCount
if maxSegmentMatchType == MatchTypeMultipleSegments {
maxMatchableSegments = greedyPatternMaxMatchableSegments
}
segments = segments[0:pathSegmentsCount]
return &Pattern{
caseInsensitive: caseInsensitive,
captureVarsLen: captureVarsLen,
maxMatchableSegments: maxMatchableSegments,
priority: computePriority(segments),
segments: segments,
RawValue: pathPattern,
Attachment: nil,
}, nil
}
func regexSegmentMatch(urlPathSegment string, patternSegment string, caseInsensitive bool) bool {
var hasStar bool
patternSegmentLen := len(patternSegment)
urlPathSegmentLen := len(urlPathSegment)
for i := 0; i < patternSegmentLen; i++ {
if patternSegment[i] == '*' {
hasStar = true
break
}
}
if !hasStar && urlPathSegmentLen != patternSegmentLen {
return false
}
runesMatches := func(uc uint8, pc uint8) bool {
if pc == '?' {
return true
}
if caseInsensitive {
return unicode.ToUpper(rune(uc)) == unicode.ToUpper(rune(pc))
} else {
return uc == pc
}
}
var pIndex int
var uIndex int
var checkPointRestore bool
pIndexCheckPoint := -1
uIndexCheckPoint := -1
for {
if pIndex == patternSegmentLen && uIndex == urlPathSegmentLen {
return true
}
if pIndex == patternSegmentLen || uIndex == urlPathSegmentLen {
checkPointRestore = true
}
if checkPointRestore {
// no checkpoint, meaning that no greedy character found
if pIndexCheckPoint == -1 || uIndexCheckPoint == -1 {
return false
}
pIndex = pIndexCheckPoint
uIndex = uIndexCheckPoint + 1
}
checkPointRestore = false
uc := urlPathSegment[uIndex]
pc := patternSegment[pIndex]
if pc == '?' {
pIndex++
uIndex++
} else if pc == '*' {
//skip the next * if exists (example ab****)
for i := pIndex + 1; i < patternSegmentLen; i++ {
if patternSegment[i] != '*' {
pIndex = i - 1
break
}
}
if pIndex == patternSegmentLen-1 {
//the * is the last character in the pattern and matches the rest of the text
return true
}
pIndexCheckPoint = -1
uIndexCheckPoint = -1
pc = patternSegment[pIndex+1]
for ; uIndex < urlPathSegmentLen; uIndex++ {
uc = urlPathSegment[uIndex]
if runesMatches(uc, pc) {
// we save the checkpoint and we continue with the next matching
pIndexCheckPoint = pIndex
uIndexCheckPoint = uIndex
pIndex++
break
}
}
} else {
if runesMatches(uc, pc) {
pIndex++
uIndex++
} else {
checkPointRestore = true
}
}
}
}
func determineMatchTypeForSegment(pathSegment string) MatchType {
if pathSegment == "*" {
return MatchTypeSingleSegment
} else if pathSegment == "**" {
return MatchTypeMultipleSegments
}
if pathSegment[0] == '{' && pathSegment[len(pathSegment)-1] == '}' {
for pos := 0; pos < len(pathSegment); pos++ {
ch := pathSegment[pos]
if ch == ':' {
return MatchTypeConstraintCaptureVar
}
}
return MatchTypeCaptureVar
}
for pos := 0; pos < len(pathSegment); pos++ {
ch := pathSegment[pos]
if ch == '?' || ch == '*' {
return MatchTypeRegex
}
}
return MatchTypeLiteral
}
func validatePathSegment(pathSegment string) error {
pathSegmentLen := len(pathSegment)
if pathSegmentLen == 0 {
return errors.New("empty path segment")
}
if pathSegment[0] == '{' && pathSegment[pathSegmentLen-1] != '}' {
return errors.New("opened bracket without being closed")
}
if pathSegment[pathSegmentLen-1] == '}' && pathSegment[0] != '{' {
return errors.New("closed bracket without being opened")
}
if pathSegment[0] == '{' && pathSegment[pathSegmentLen-1] == '}' {
if pathSegmentLen == 2 {
return errors.New("empty capture variable name")
}
for pos := 1; pos < pathSegmentLen-1; pos++ {
if pathSegment[pos] == ':' {
if pos == 1 {
return errors.New("empty capture variable name")
}
if pos == pathSegmentLen-2 {
return errors.New("empty capture regex constraint")
}
}
}
}
if pathSegment == "*" || pathSegment == "**" {
return nil
}
var consecutiveAsterixCount int
for pos := 0; pos < pathSegmentLen; pos++ {
if pathSegment[pos] == '*' {
consecutiveAsterixCount++
} else {
consecutiveAsterixCount = 0
}
if consecutiveAsterixCount >= 2 {
return errors.New("not allowed two or more consecutive asterix together with other characters")
}
}
return nil
}