-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegment.go
73 lines (56 loc) · 1.51 KB
/
segment.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
package confiq
import (
"strconv"
"strings"
)
const (
segmentDividerChar = "."
openBraceChar = "["
closeBraceChar = "]"
)
type segment interface {
String() string
}
type keySegment string
func (kS keySegment) String() string {
return string(kS)
}
func (kS keySegment) asString() string {
return string(kS)
}
type indexSegment int
func (iS indexSegment) String() string {
return openBraceChar + strconv.Itoa(int(iS)) + closeBraceChar
}
func (iS indexSegment) asInt() int {
return int(iS)
}
func getNextSegment(path string) (segment, string) {
var (
nextSegment, remainingPath string
segmentDividerIndex = strings.Index(path, segmentDividerChar)
)
if segmentDividerIndex == -1 {
nextSegment = path
remainingPath = ""
} else {
nextSegment = path[:segmentDividerIndex]
remainingPath = path[segmentDividerIndex+1:]
}
openBraceIndex := strings.Index(path, openBraceChar)
if openBraceIndex == -1 {
return keySegment(nextSegment), remainingPath
}
closeBraceIndex := strings.Index(nextSegment, closeBraceChar)
if closeBraceIndex == -1 || closeBraceIndex < openBraceIndex {
return keySegment(nextSegment), remainingPath
}
if openBraceIndex != 0 {
return keySegment(nextSegment[:openBraceIndex]), nextSegment[openBraceIndex:closeBraceIndex+1] + segmentDividerChar + remainingPath
}
index := nextSegment[openBraceIndex+1 : closeBraceIndex]
if indexInt, err := strconv.Atoi(index); err == nil {
return indexSegment(indexInt), remainingPath
}
return keySegment(index), remainingPath
}