-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfixer-reader.go
61 lines (52 loc) · 1.04 KB
/
fixer-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
package kiwitaxi
import (
"bufio"
"bytes"
"io"
"strings"
)
type FixerReader struct {
rBuf *bufio.Reader
wBuf *bytes.Buffer
replacer *strings.Replacer
columns int
}
func NewFixerReader(r io.Reader) *FixerReader {
return &FixerReader{
rBuf: bufio.NewReader(r),
wBuf: bytes.NewBuffer([]byte{}),
replacer: strings.NewReplacer("\\N", ""),
columns: -1,
}
}
func (f *FixerReader) Read(p []byte) (n int, err error) {
if f.wBuf.Len() == 0 {
data, _, err := f.rBuf.ReadLine()
if err != nil {
return n, err
}
if len(data) == 0 {
return 0, io.EOF
}
// skip bad line
if !f.checkColumn(data) {
return 0, nil
}
f.wBuf.Write(f.fixLine(data))
}
n, _ = f.wBuf.Read(p)
return
}
func (f *FixerReader) checkColumn(line []byte) bool {
countColumns := strings.Count(string(line), "\t")
if f.columns == -1 {
f.columns = countColumns
}
if f.columns != countColumns {
return false
}
return true
}
func (f *FixerReader) fixLine(line []byte) []byte {
return []byte(f.replacer.Replace(string(line)) + "\n")
}