-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplit.go
81 lines (73 loc) · 1.61 KB
/
split.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
package sie
import (
"bufio"
"strings"
"unicode/utf8"
)
func splitWords(s string) []string {
sc := bufio.NewScanner(strings.NewReader(s))
sc.Split(scanWords)
var res []string
for sc.Scan() {
res = append(res, maybeUnquote(sc.Text()))
}
return res
}
func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Skip leading spaces.
start := 0
for width := 0; start < len(data); start += width {
var r rune
r, width = utf8.DecodeRune(data[start:])
if !isSpace(r) {
break
}
}
// Check for leading quote or bracket
inQuote := false
inBrackets := false
if r, width := utf8.DecodeRune(data[start:]); r == '"' {
start += width
inQuote = true
} else if r == '{' {
start += width
inBrackets = true
}
// Scan until space or end quote, marking end of word.
inEscape := false
for width, i := 0, start; i < len(data); i += width {
var r rune
r, width = utf8.DecodeRune(data[i:])
if !inEscape && r == '\\' {
inEscape = true
continue
}
if !inQuote && !inBrackets && isSpace(r) {
return i + width, data[start:i], nil
}
if !inEscape && !inQuote && inBrackets && r == '}' {
return i + width, data[start:i], nil
}
if !inEscape && inQuote && r == '"' {
if !inBrackets {
return i + width, data[start:i], nil
}
inQuote = false
}
inEscape = false
}
// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
if atEOF && len(data) > start {
return len(data), data[start:], nil
}
// Request more data.
return start, nil, nil
}
func isSpace(r rune) bool {
switch r {
case ' ', '\t':
return true
default:
return false
}
}