-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.go
66 lines (53 loc) · 1.18 KB
/
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
57
58
59
60
61
62
63
64
65
66
package csv
import (
"io"
)
// Reader can be used to read CSV formatted data from an io.Reader
type Reader struct {
t tokenizer
}
// NewReader returns a Reader ready to start reading CSV formatted data from the given source
func NewReader(r io.Reader) *Reader {
return &Reader{newTokenizer(r)}
}
// Read reads and returns the next record from the source
func (r *Reader) Read() ([]string, error) {
var (
record []string
field string
token token
err error
)
for err == nil {
token, err = r.t.readToken()
// text
if token.kind == text {
field += token.value
}
// end of field
if token.kind == comma || token.kind == lineBreak || token.kind == eof && (r.t.onFirstLine || field != "") {
record = append(record, field)
field = ""
}
// end of record
if token.kind == lineBreak || token.kind == eof {
break
}
}
return record, err
}
// ReadAll reads and returns all remaining records from the source
func (r *Reader) ReadAll() ([][]string, error) {
var (
records [][]string
record []string
err error
)
for err == nil {
record, err = r.Read()
if len(record) > 0 {
records = append(records, record)
}
}
return records, err
}