-
Notifications
You must be signed in to change notification settings - Fork 0
/
qsplit.go
74 lines (61 loc) · 1.22 KB
/
qsplit.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
package qsplit
import (
"unicode"
)
func Split(str string) ([]string,error) {
fields := make([]string, 0)
runes := make([]rune, 0)
var inquote, escaped bool
loop:
for _,r := range(str) {
switch inquote {
case true:
switch escaped {
case true:
switch r {
case '"':
runes = append(runes, r)
case 'n':
runes = append(runes, '\n')
case '\\':
runes = append(runes, '\\')
default:
return nil, SplitError{Type: InvalidEscapedCharacter, Data: string(r)}
}
escaped = false
case false:
if r == '"' {
inquote = false
if len(runes) > 0 {
fields = append(fields, string(runes))
runes = make([]rune, 0)
}
} else if r == '\\' {
escaped = true
} else {
runes = append(runes, r)
}
}
case false:
if unicode.IsSpace(r) {
if len(runes) > 0 {
fields = append(fields, string(runes))
runes = make([]rune, 0)
}
} else if r =='#' {
break loop
} else if r == '"' {
inquote = true
} else {
runes = append(runes, r)
}
}
}
if inquote {
return nil,SplitError{Type: UnterminatedQuote}
}
if len(runes) > 0 {
fields = append(fields, string(runes))
}
return fields,nil
}