-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathstringfields.go
More file actions
58 lines (49 loc) · 1.11 KB
/
Copy pathstringfields.go
File metadata and controls
58 lines (49 loc) · 1.11 KB
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
package main
// StringFields tokenizes an input string into an array of separate fields. It
// supports quotes. It doesn't parse escape sequences.
func StringFields(input string) []string {
var ret []string = make([]string, 0)
var tmp string
flush := func() {
if len(tmp) > 0 {
ret = append(ret, tmp)
tmp = ""
}
}
type parseState int
const (
Normal parseState = iota
InsideDoubleQuotes
InsideSingleQuotes
)
var state parseState = Normal
for _, r := range input {
if state == Normal {
if r == '"' {
state = InsideDoubleQuotes
} else if r == '\'' {
state = InsideSingleQuotes
} else if r == ' ' || r == '\t' || r == '\n' || r == '\r' {
flush()
} else {
tmp += string(r)
}
} else if state == InsideDoubleQuotes {
if r == '"' {
state = Normal // Don't flush yet, might be switching quote types mid-field
} else {
tmp += string(r)
}
} else if state == InsideSingleQuotes {
if r == '\'' {
state = Normal
} else {
tmp += string(r)
}
} else {
panic("invalid state") // unreachable
}
}
flush() // any incomplete fields
return ret
}