-
Notifications
You must be signed in to change notification settings - Fork 0
/
split.go
118 lines (105 loc) · 2.59 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
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
package xre
import "bytes"
func trimmedSplitter(sp splitter, cutset string) splitter {
switch impl := sp.(type) {
case lineSplitter:
// TODO would do better to leverage a generic one around lineSpliter,
// or even just ignore if cutset is just \r and/or \n
if impl == 1 {
return byteSplitTrimmer{'\n', cutset}
}
return bytesSplitTrimmer{bytes.Repeat([]byte{'\n'}, int(impl)), cutset}
case byteSplitter:
return byteSplitTrimmer{byte(impl), cutset}
case bytesSplitter:
return bytesSplitTrimmer{impl, cutset}
default:
panic("generic split trimming not implemented")
}
}
type lineSplitter int
type byteSplitter byte
type bytesSplitter []byte
type byteSplitTrimmer struct {
delim byte
cutset string
}
type bytesSplitTrimmer struct {
delim []byte
cutset string
}
func (ls lineSplitter) Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
// TODO CR support
attempt:
for off := 0; ; {
i := bytes.IndexByte(data[off:], '\n')
if i < 0 {
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
}
i += off
j := i + 1
for n := 1; n < int(ls) && j < len(data); n++ {
if data[j] == '\n' {
j++
} else {
off = j
continue attempt
}
}
return j, data[0:i], nil
}
}
func (bs byteSplitter) Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, byte(bs)); i >= 0 {
return i + 1, data[0:i], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
}
func (bss bytesSplitter) Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, bss); i >= 0 {
return i + len(bss), data[0:i], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
}
func (bst byteSplitTrimmer) Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, bst.delim); i >= 0 {
return i + 1, bytes.Trim(data[0:i], bst.cutset), nil
}
if atEOF {
return len(data), bytes.Trim(data, bst.cutset), nil
}
return 0, nil, nil
}
func (bsst bytesSplitTrimmer) Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, bsst.delim); i >= 0 {
return i + len(bsst.delim), bytes.Trim(data[0:i], bsst.cutset), nil
}
if atEOF {
return len(data), bytes.Trim(data, bsst.cutset), nil
}
return 0, nil, nil
}