forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_reader.go
56 lines (49 loc) · 961 Bytes
/
csv_reader.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
package csvsplitter
import (
"bufio"
"bytes"
"io"
)
type CSVReader struct {
reader *bufio.Reader
delim byte
buf *bytes.Buffer
}
func NewCSVReader(r io.Reader, delim byte) *CSVReader {
return &CSVReader{
reader: bufio.NewReader(r),
delim: delim,
buf: bytes.NewBuffer(make([]byte, 0, 1024)),
}
}
// ReadRecord returns a keyspaceId and a line from which it was
// extracted, with the keyspaceId stripped.
func (r CSVReader) ReadRecord() (line []byte, err error) {
defer r.buf.Reset()
escaped := false
inQuote := false
for {
b, err := r.reader.ReadByte()
if err != nil {
// Assumption: the csv file ends with a
// newline. Otherwise io.EOF should be treated
// separately.
return nil, err
}
r.buf.WriteByte(b)
if escaped {
escaped = false
continue
}
switch b {
case '\\':
escaped = true
case '"':
inQuote = !inQuote
case '\n':
if !inQuote {
return r.buf.Bytes(), nil
}
}
}
}