-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi.go
78 lines (63 loc) · 1.87 KB
/
multi.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
package multicsv
import (
"io"
)
type Reader interface {
Read() (record []string, err error)
}
type eofReader struct{}
func (eofReader) Read() (record []string, err error) {
return []string{}, io.EOF
}
// MultiReader is the logical concatenation of the provided input readers.
// They're read sequentially. Once all inputs have returned EOF, Read will return EOF.
// If any of the readers return a non-nil, non-EOF error, Read will return that error.
type MultiReader struct {
readers []Reader
}
// Read reads one record (a slice of fields) from the provided input readers.
// Following code was taken from https://go.dev/src/io/multi.go and adopted to works with csv readers.
func (mr *MultiReader) Read() (record []string, err error) {
for len(mr.readers) > 0 {
if len(mr.readers) == 1 {
if r, ok := mr.readers[0].(*MultiReader); ok {
mr.readers = r.readers
continue
}
}
record, err = mr.readers[0].Read()
if err == io.EOF {
mr.readers[0] = eofReader{} // permit earlier GC
mr.readers = mr.readers[1:]
}
if len(record) > 0 || err != io.EOF {
if err == io.EOF && len(mr.readers) > 0 {
err = nil
}
return
}
}
return []string{}, io.EOF
}
// ReadAll reads all the remaining records from the provided input readers.
func (mr *MultiReader) ReadAll() (records [][]string, err error) {
for {
record, err := mr.Read()
if err == io.EOF {
return records, nil
}
if err != nil {
return nil, err
}
records = append(records, record)
}
}
// NewReader returns a Reader that's the logical concatenation of
// the provided input readers. They're read sequentially. Once all
// inputs have returned EOF, Read will return EOF. If any of the readers
// return a non-nil, non-EOF error, Read will return that error.
func NewReader(readers ...Reader) *MultiReader {
r := make([]Reader, len(readers))
copy(r, readers)
return &MultiReader{r}
}