-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseroutes.go
882 lines (799 loc) · 23 KB
/
parseroutes.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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
package compiler
import (
"bufio"
"fmt"
"io"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
type routeElementKind int
const (
illegalCodePoint routeElementKind = iota
illegalQuestionMark routeElementKind = iota
illegalHash routeElementKind = iota
illegalWhitespace routeElementKind = iota
illegalCharInParamName routeElementKind = iota
illegalBackslashEscape routeElementKind = iota
slash routeElementKind = iota
constant routeElementKind = iota
parameter routeElementKind = iota
integerParameter routeElementKind = iota
restParameter routeElementKind = iota
singleGlob routeElementKind = iota
doubleGlob routeElementKind = iota
noTrailingSlash routeElementKind = iota
)
func (k routeElementKind) String() string {
switch k {
case illegalCodePoint:
return "<illegal-code-point>"
case illegalQuestionMark:
return "?"
case illegalHash:
return "#"
case illegalWhitespace:
return "<illegal-whitespace>"
case illegalCharInParamName:
return "<illegal-param-name-char>"
case illegalBackslashEscape:
return "<illegal-backslash-escape>"
case slash:
return "/"
case constant:
return "const"
case parameter:
return "param"
case integerParameter:
return "integerParam"
case restParameter:
return "restParam"
case singleGlob:
return "*"
case doubleGlob:
return "**"
case noTrailingSlash:
return "!/"
}
panic(fmt.Sprintf("Unrecognized routeElementKind %v", int(k)))
}
type routeElement struct {
kind routeElementKind
value string
}
func badCodePoint(r rune) bool {
return r == 0 || (unicode.IsControl(r) && r != '\t' && r != '\n' && r != '\r')
}
func parseRoute(route string) []routeElement {
elems := make([]routeElement, 0)
// all special chars are ASCII so we can iterate by byte
currentElem := routeElement{}
for i := 0; i < len(route); {
b := route[i]
currentElem = routeElement{}
switch b {
case '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x0B', '\x0C', '\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F':
i++
currentElem.kind = illegalCodePoint
case '?':
i++
currentElem.kind = illegalQuestionMark
case '#':
i++
currentElem.kind = illegalHash
case '/':
i++
currentElem.kind = slash
case '!':
if i == len(route)-2 && route[i+1] == '/' {
i += 2
currentElem.kind = noTrailingSlash
} else {
i++
currentElem.kind = constant
currentElem.value = "!"
}
case '*':
if i+1 < len(route) && route[i+1] == '*' {
i += 2
currentElem.kind = doubleGlob
} else {
i++
currentElem.kind = singleGlob
}
case ':':
startI := i
isInteger := false
isRest := false
if i+1 < len(route) && route[i+1] == '#' {
isInteger = true
i++
} else if i+2 < len(route) && route[i+1] == '*' && route[i+2] == '*' {
isRest = true
i += 2
}
var badEscape bool
var sb strings.Builder
nameStartI := i
i++
if nameStartI+1 < len(route) && route[nameStartI+1] == '{' {
i++
if route[nameStartI+1] != '{' {
i += 2
}
badChar := false
for i < len(route) {
if route[i] == '}' {
i++
break
}
if route[i] == '\\' && i+1 < len(route) {
i++
if route[i] != '\\' && route[i] != '}' && route[i] != '#' {
badEscape = true
}
}
r, l := utf8.DecodeRuneInString(route[i:])
if r == 0 || (unicode.IsSpace(r) && r != ' ') || badCodePoint(r) {
badChar = true
}
sb.WriteRune(r)
i += l
}
if sb.Len() == 0 {
currentElem.kind = constant
currentElem.value = ":{}"
} else {
currentElem.kind = parameter
if isInteger {
currentElem.kind = integerParameter
} else if isRest {
currentElem.kind = restParameter
}
currentElem.value = sb.String()
}
if badChar {
elems = append(elems, routeElement{illegalCharInParamName, ""})
}
} else {
for i < len(route) {
if route[i] == '\\' && i+1 < len(route) {
i++
if route[i] != '\\' && route[i] != ':' && route[i] != '#' {
badEscape = true
}
sb.WriteByte(route[i])
i++
} else {
r, l := utf8.DecodeRuneInString(route[i:])
if r == '_' || unicode.IsLetter(r) || unicode.IsNumber(r) {
sb.WriteRune(r)
i += l
} else {
break
}
}
}
if sb.Len() == 0 {
currentElem.kind = constant
currentElem.value = route[startI:i]
} else {
currentElem.kind = parameter
if isInteger {
currentElem.kind = integerParameter
} else if isRest {
currentElem.kind = restParameter
}
currentElem.value = sb.String()
}
}
if badEscape {
elems = append(elems, routeElement{illegalBackslashEscape, ""})
}
default:
currentElem.kind = constant
var sb strings.Builder
for i < len(route) && route[i] != '/' && route[i] != '!' && route[i] != '*' && route[i] != ':' && route[i] != '?' && route[i] != '#' {
if route[i] == '\\' {
i++
if i == len(route) {
sb.WriteByte('\\')
} else if route[i] == '\\' || route[i] == ':' || route[i] == '!' || route[i] == '[' || route[i] == ']' || route[i] == '*' {
sb.WriteByte(route[i])
i++
} else {
currentElem.value = sb.String()
elems = append(elems, currentElem)
elems = append(elems, routeElement{illegalBackslashEscape, ""})
currentElem.kind = constant
currentElem.value = string(route[i])
sb.Reset()
i++
}
} else {
r, l := utf8.DecodeRuneInString(route[i:])
if unicode.IsSpace(r) {
currentElem.value = sb.String()
elems = append(elems, currentElem)
elems = append(elems, routeElement{illegalWhitespace, ""})
currentElem.kind = constant
currentElem.value = ""
sb.Reset()
} else if badCodePoint(r) {
currentElem.value = sb.String()
elems = append(elems, currentElem)
elems = append(elems, routeElement{illegalCodePoint, ""})
currentElem.kind = constant
currentElem.value = ""
sb.Reset()
} else {
sb.WriteString(route[i : i+l])
}
i += l
}
}
currentElem.value = sb.String()
}
elems = append(elems, currentElem)
}
return elems
}
func validateRouteElems(initialIndent, indent int, elems []routeElement) []RouteErrorKind {
if len(elems) == 0 {
return []RouteErrorKind{MissingNameOrRoute}
}
var errors []RouteErrorKind
for i := 0; i < len(elems)-1; i++ {
if elems[i].kind == slash && elems[i+1].kind == slash {
errors = append(errors, MultipleSlashesInARow)
break
}
}
if (initialIndent == -1 || indent == initialIndent) && elems[0].kind != slash {
errors = append(errors, RootMustStartWithSlash)
}
if elems[len(elems)-1].kind == noTrailingSlash {
if len(elems) == 1 {
errors = append(errors, OnlyNoTrailingSlash)
} else if elems[len(elems)-1].kind == slash {
errors = append(errors, NoTrailingSlashAfterSlash)
}
}
return errors
}
type RouteFileEntry struct {
indent int
name string
pattern []routeElement
line int
terminal bool // if false, the route exists only as a parent of other routes
tags map[string]struct{}
methods map[string]struct{}
}
type RouteErrorKind int
const (
MissingNameOrRoute RouteErrorKind = iota
DuplicateRouteName RouteErrorKind = iota
RootMustStartWithSlash RouteErrorKind = iota
OverlappingRoutes RouteErrorKind = iota
MisplacedDot RouteErrorKind = iota
RouteContainsBadCodePoint RouteErrorKind = iota
QuestionMarkInRoute RouteErrorKind = iota
HashInRoute RouteErrorKind = iota
WhitespaceInRoute RouteErrorKind = iota
IllegalCharInParamName RouteErrorKind = iota
IllegalBackslashEscape RouteErrorKind = iota
IllegalBackslashEscapeInRouteName RouteErrorKind = iota
NontabspaceIndentationCharacter RouteErrorKind = iota
BadCharacterInMethodName RouteErrorKind = iota
MissingCommaBetweenMethodNames RouteErrorKind = iota
TwoCommasInSequenceInMethodNames RouteErrorKind = iota
IndentLessThanFirstLine RouteErrorKind = iota
OnlyNoTrailingSlash RouteErrorKind = iota
NoTrailingSlashAfterSlash RouteErrorKind = iota
MultipleSlashesInARow RouteErrorKind = iota
IOError RouteErrorKind = iota
)
type RouteError struct {
Kind RouteErrorKind
Line int
DuplicateName string
OtherLine int
IOError error
Filenames []string
}
func (e RouteError) Error() string {
var desc string
switch e.Kind {
case MissingNameOrRoute:
desc = "missing route name or missing route pattern"
case DuplicateRouteName:
desc = fmt.Sprintf("two non-adjacently-nestled routes have the same name ('%v'); move them next to each other in the same file", e.DuplicateName)
case RootMustStartWithSlash:
desc = "pattern at root level must start with '/'"
case OverlappingRoutes:
desc = "routes overlap"
case MisplacedDot:
desc = "misplaced '.': should come immediately after parent route and be indented under it"
case RouteContainsBadCodePoint:
desc = "route contains bad code point"
case NontabspaceIndentationCharacter:
desc = "route is indented with a whitespace character other than a tab or a space"
case QuestionMarkInRoute:
desc = "route may not contain '?'"
case HashInRoute:
desc = "route may not contain '#'"
case WhitespaceInRoute:
desc = "route may not contain whitespace"
case IllegalBackslashEscape:
desc = "illegal backslash escape"
case IllegalBackslashEscapeInRouteName:
desc = "illegal backslash escape in route name"
case BadCharacterInMethodName:
desc = "bad character in method name"
case MissingCommaBetweenMethodNames:
desc = "missing comma between method names"
case TwoCommasInSequenceInMethodNames:
desc = "two commas in sequence in list of method names"
case IndentLessThanFirstLine:
desc = "the line is indented less than the first non-blank line of the input file"
case OnlyNoTrailingSlash:
desc = "the route consists entirely of a '!/' prohibition on trailing slashes"
case NoTrailingSlashAfterSlash:
desc = "the '!/' sequence banning trailing slashes follows a slash"
case MultipleSlashesInARow:
desc = "multiple slashes in a row in route"
case IOError:
desc = fmt.Sprintf("IO Error: %v", e.IOError)
default:
panic(fmt.Sprintf("unrecognized routeRrrorKind %v", int(e.Kind)))
}
if len(e.Filenames) == 0 {
return fmt.Sprintf("stdin line %v: %v", e.Line, desc)
}
if e.OtherLine == 0 {
return fmt.Sprintf("%v line %v: %v", e.Filenames[0], e.Line, desc)
}
if e.OtherLine != 0 && len(e.Filenames) == 2 {
return fmt.Sprintf("(%v line %v; %v line %v): %v", e.Filenames[0], e.Line, e.Filenames[1], e.OtherLine, desc)
}
// shouldn't get here
return fmt.Sprintf("(line %v; line %v): %v", e.Line, e.OtherLine, desc)
}
func ParseRouteFile(input io.Reader) ([]RouteFileEntry, []RouteError) {
entries := make([]RouteFileEntry, 0)
errors := make([]RouteError, 0)
var currentLine strings.Builder
scanner := bufio.NewScanner(input)
sourceLine := 0
firstSourceLineOfSplice := 0
initialIndent := -1
dotLevel := -1
for scanner.Scan() {
line := scanner.Text()
sourceLine++
if len(line) > 0 && line[len(line)-1] == '\\' && (len(line) == 1 || line[len(line)-2] != '\\') {
currentLine.WriteString(line[:len(line)-1])
firstSourceLineOfSplice = sourceLine
continue
}
if currentLine.Len() == 0 {
firstSourceLineOfSplice = sourceLine
currentLine.WriteString(line)
} else {
// last line ended with '\', so strip leading whitespace
currentLine.WriteString(stripLeadingWhitespace(line))
}
wholeLine := currentLine.String()
currentLine.Reset()
wholeLine = stripTrailingWhitespace(stripComment(wholeLine))
if isBlank(wholeLine) {
continue
}
indent := 0
for i := 0; i < len(wholeLine); {
nextr, sz := utf8.DecodeRuneInString(wholeLine[i:])
if unicode.IsSpace(nextr) {
if nextr != ' ' && nextr != '\t' {
errors = append(errors, RouteError{NontabspaceIndentationCharacter, sourceLine, "", 0, nil, []string{}})
}
indent++
i += sz
} else if badCodePoint(nextr) {
errors = append(errors, RouteError{IllegalBackslashEscapeInRouteName, sourceLine, "", 0, nil, []string{}})
i += sz
} else {
break
}
}
if indent < initialIndent {
errors = append(errors, RouteError{IndentLessThanFirstLine, sourceLine, "", 0, nil, []string{}})
continue
}
if initialIndent == -1 {
initialIndent = indent
}
// Is it '.'?
if isDot(wholeLine) {
if len(entries) == 0 || entries[len(entries)-1].indent >= indent {
errors = append(errors, RouteError{MisplacedDot, sourceLine, "", 0, nil, []string{}})
}
dotLevel = indent
continue
} else if indent < dotLevel {
dotLevel = -1
}
if len(entries) != 0 && entries[len(entries)-1].indent < indent && dotLevel < indent {
entries[len(entries)-1].terminal = false
}
var nameB strings.Builder
i := indent
for i < len(wholeLine) {
if wholeLine[i] == '\\' {
if i+1 < len(wholeLine) {
rn, sz := utf8.DecodeRuneInString(wholeLine[i+1:])
nameB.WriteRune(rn)
i += sz + 1
if badCodePoint(rn) {
errors = append(errors, RouteError{RouteContainsBadCodePoint, sourceLine, "", 0, nil, []string{}})
}
if !unicode.IsSpace(rn) {
errors = append(errors, RouteError{IllegalBackslashEscapeInRouteName, sourceLine, "", 0, nil, []string{}})
}
} else {
errors = append(errors, RouteError{IllegalBackslashEscapeInRouteName, sourceLine, "", 0, nil, []string{}})
i++
}
} else {
rn, sz := utf8.DecodeRuneInString(wholeLine[i:])
i += sz
if unicode.IsSpace(rn) {
break
}
if badCodePoint(rn) {
errors = append(errors, RouteError{RouteContainsBadCodePoint, sourceLine, "", 0, nil, []string{}})
} else {
nameB.WriteRune(rn)
}
}
}
name := nameB.String()
for i < len(wholeLine) {
rn, sz := utf8.DecodeRuneInString(wholeLine[i:])
if badCodePoint(rn) {
errors = append(errors, RouteError{RouteContainsBadCodePoint, sourceLine, "", 0, nil, []string{}})
}
if !unicode.IsSpace(rn) {
break
}
i += sz
}
if i >= len(wholeLine) {
errors = append(errors, RouteError{MissingNameOrRoute, firstSourceLineOfSplice, "", 0, nil, []string{}})
continue
}
methods := make(map[string]struct{}, 0)
if wholeLine[i] == '[' {
i++
var currentMethod strings.Builder
foundComma := false
for i < len(wholeLine) {
rn, sz := utf8.DecodeRuneInString(wholeLine[i:])
i += sz
if unicode.IsSpace(rn) || rn == ',' || rn == ']' {
if currentMethod.Len() > 0 {
methods[strings.ToUpper(currentMethod.String())] = struct{}{}
currentMethod.Reset()
}
if rn == ',' {
if foundComma {
errors = append(errors, RouteError{TwoCommasInSequenceInMethodNames, sourceLine, "", 0, nil, []string{}})
}
foundComma = true
}
} else if badCodePoint(rn) {
errors = append(errors, RouteError{RouteContainsBadCodePoint, sourceLine, "", 0, nil, []string{}})
} else if (rn >= 'A' && rn <= 'Z') || (rn >= 'a' || rn <= 'z') { // ASCII letters only for method names
if len(methods) > 0 && currentMethod.Len() == 0 && !foundComma {
errors = append(errors, RouteError{MissingCommaBetweenMethodNames, sourceLine, "", 0, nil, []string{}})
}
foundComma = false
currentMethod.WriteRune(rn)
} else {
errors = append(errors, RouteError{BadCharacterInMethodName, sourceLine, "", 0, nil, []string{}})
}
if rn == ']' {
break
}
}
}
if len(methods) == 0 {
methods["GET"] = struct{}{}
}
for i < len(wholeLine) {
rn, sz := utf8.DecodeRuneInString(wholeLine[i:])
if badCodePoint(rn) {
errors = append(errors, RouteError{RouteContainsBadCodePoint, sourceLine, "", 0, nil, []string{}})
}
if !unicode.IsSpace(rn) {
break
}
i += sz
}
patternString := wholeLine[i:]
tags, tagsStart := getTags(patternString)
patternString = patternString[0:tagsStart]
pattern := parseRoute(patternString)
validationErrorKinds := validateRouteElems(initialIndent, indent, pattern)
if len(validationErrorKinds) > 0 {
for _, k := range validationErrorKinds {
errors = append(errors, RouteError{k, firstSourceLineOfSplice, "", 0, nil, []string{}})
}
continue
}
for _, elem := range pattern {
switch elem.kind {
case illegalCodePoint:
errors = append(errors, RouteError{RouteContainsBadCodePoint, sourceLine, "", 0, nil, []string{}})
case illegalQuestionMark:
errors = append(errors, RouteError{QuestionMarkInRoute, sourceLine, "", 0, nil, []string{}})
case illegalHash:
errors = append(errors, RouteError{HashInRoute, sourceLine, "", 0, nil, []string{}})
case illegalWhitespace:
errors = append(errors, RouteError{WhitespaceInRoute, sourceLine, "", 0, nil, []string{}})
case illegalCharInParamName:
errors = append(errors, RouteError{IllegalCharInParamName, sourceLine, "", 0, nil, []string{}})
case illegalBackslashEscape:
errors = append(errors, RouteError{IllegalBackslashEscape, sourceLine, "", 0, nil, []string{}})
}
}
notionalIndent := indent
if indent == initialIndent {
// Ensure initial indent is consistent across files
notionalIndent = 0
}
entries = append(entries, RouteFileEntry{
indent: notionalIndent,
name: name,
pattern: pattern,
line: firstSourceLineOfSplice,
terminal: true,
tags: tags,
methods: methods,
})
}
if err := scanner.Err(); err != nil {
errors = append(errors, RouteError{IOError, sourceLine, "", 0, nil, []string{}})
}
return entries, errors
}
func ParseRouteFiles(inputFiles []string, inputReaders []io.Reader) ([][]RouteFileEntry, []RouteError) {
if len(inputFiles) != len(inputReaders) {
panic("Bad arguments passed to 'ParseRouteFiles': inputFiles and inputReaders must have same length")
}
entriesPerFile := make([][]RouteFileEntry, len(inputReaders))
allErrors := make([][]RouteError, len(inputReaders))
var wg sync.WaitGroup
for i, r := range inputReaders {
wg.Add(1)
ii := i // for Go < 1.20 compat
rr := r // ditto
go func() {
defer wg.Done()
ent, es := ParseRouteFile(rr)
for j := range es {
es[j].Filenames = []string{inputFiles[ii]}
}
entriesPerFile[ii] = ent
allErrors[ii] = es
}()
}
wg.Wait()
return entriesPerFile, flatten(allErrors)
}
func stripLeadingWhitespace(line string) string {
for i := 0; i < len(line); {
rn, sz := utf8.DecodeRuneInString(line[i:])
if !unicode.IsSpace(rn) {
return line[i:]
}
i += sz
}
return ""
}
func stripTrailingWhitespace(line string) string {
for i := len(line); i > 0; {
rn, sz := utf8.DecodeLastRuneInString(line[0:i])
if !unicode.IsSpace(rn) {
return line[0:i]
}
i -= sz
}
return ""
}
func stripComment(line string) string {
var b strings.Builder
for i := range line {
if line[i] == '#' && (i == 0 || line[i-1] != ':') {
// there's a hash not preceded by a ':'
if i > 0 && line[i-1] == '\\' && (i-2 < 0 || line[i-2] != '\\') {
// it's escaped, so it's not a comment.
if b.Len() == 0 {
b.WriteString(line[0 : i-1])
}
b.WriteByte('#')
} else {
// it's not escaped, so it is the start of a comment
if b.Len() > 0 {
return b.String()
}
return line[0:i]
}
} else if b.Len() > 0 {
// we can't use a subslice of the input string because of an escaped '#',
// so copy the char to a new string.
b.WriteByte(line[i])
}
}
if b.Len() > 0 {
return b.String()
}
return line
}
func getTags(routeString string) (map[string]struct{}, int) {
hasTags := false
var ti int
for ti = len(routeString); ti >= 0; {
rn, sz := utf8.DecodeLastRuneInString(routeString[0:ti])
if rn == ']' && routeString[ti-1] != '\\' {
hasTags = true
ti--
break
}
if !unicode.IsSpace(rn) {
break
}
ti -= sz
}
if !hasTags {
return map[string]struct{}{}, len(routeString)
}
ti--
tags := make(map[string]struct{})
currentTag := make([]byte, len(routeString))
currentTagI := len(currentTag) - 1
leftmostNonwhitespaceI := len(currentTag)
rightmostNonwhitespaceI := len(currentTag)
foundRightmostNonwhitespace := false
for ti >= 0 {
if routeString[ti] == ',' || routeString[ti] == '[' || routeString[ti] == ']' {
if ti > 0 && routeString[ti-1] == '\\' {
leftmostNonwhitespaceI = currentTagI
if !foundRightmostNonwhitespace {
rightmostNonwhitespaceI = currentTagI + 1
foundRightmostNonwhitespace = true
}
currentTag[currentTagI] = routeString[ti]
currentTagI--
ti -= 2
} else {
tagStr := string(currentTag[leftmostNonwhitespaceI:rightmostNonwhitespaceI])
if tagStr != "" {
tags[tagStr] = struct{}{}
}
currentTagI = len(currentTag) - 1
leftmostNonwhitespaceI = len(currentTag)
rightmostNonwhitespaceI = len(currentTag)
foundRightmostNonwhitespace = false
if routeString[ti] == '[' {
break
}
ti--
}
} else {
rn, sz := utf8.DecodeLastRuneInString(routeString[0 : ti+1])
if !unicode.IsSpace(rn) || (ti-sz > 0 && routeString[ti-sz] == '\\') {
leftmostNonwhitespaceI = currentTagI - sz + 1
if !foundRightmostNonwhitespace {
rightmostNonwhitespaceI = currentTagI + 1
foundRightmostNonwhitespace = true
}
}
copy(currentTag[currentTagI-sz+1:currentTagI+1], routeString[ti-sz+1:ti+1])
currentTagI -= sz
if ti-sz > 0 && routeString[ti-sz] == '\\' {
ti--
}
ti -= sz
}
}
if ti < 0 {
// False alarm - the closing ']' made it look as if there were tags, but
// there weren't.
return map[string]struct{}{}, len(routeString)
}
for {
rn, sz := utf8.DecodeLastRuneInString(routeString[0:ti])
if !unicode.IsSpace(rn) {
break
}
ti -= sz
}
return tags, ti
}
func isDot(input string) bool {
for i, c := range input {
if unicode.IsSpace(c) {
continue
}
if c == '.' {
for _, cc := range input[i+1:] {
if !unicode.IsSpace(cc) {
return false
}
}
return true
}
return false
}
return false
}
func isBlank(s string) bool {
for _, c := range s {
if !unicode.IsSpace(c) {
return false
}
}
return true
}
func flatten[T any](a [][]T) []T {
tot := 0
for _, xs := range a {
tot += len(xs)
}
flat := make([]T, tot)
i := 0
for _, xs := range a {
for _, x := range xs {
flat[i] = x
i++
}
}
return flat
}
func debugPrintParsedRoute(route []routeElement) string {
var sb strings.Builder
for i, elem := range route {
if i != 0 {
sb.WriteRune(' ')
}
switch elem.kind {
case slash:
sb.WriteRune('/')
case constant:
sb.WriteRune('\'')
sb.WriteString(elem.value)
sb.WriteRune('\'')
case parameter:
sb.WriteString("${")
sb.WriteString(elem.value)
sb.WriteRune('}')
case integerParameter:
sb.WriteString("$#{")
sb.WriteString(elem.value)
sb.WriteRune('}')
case restParameter:
sb.WriteString("$${")
sb.WriteString(elem.value)
sb.WriteRune('}')
case singleGlob:
sb.WriteRune('*')
case doubleGlob:
sb.WriteString("**")
case noTrailingSlash:
sb.WriteString("!/")
}
}
return sb.String()
}