-
Notifications
You must be signed in to change notification settings - Fork 4
/
io.go
80 lines (76 loc) · 1.49 KB
/
io.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
package goutil
import (
"bufio"
"bytes"
"compress/gzip"
"io"
"os"
"strings"
)
// LineCount counts the number of '\n' for r
func LineCount(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}
// FileLineCount counts the number of '\n' for file f
// f could be gzip file or plain text file
func FileLineCount(f string) (int, error) {
if strings.HasSuffix(strings.ToLower(f), ".gz") {
fr, err := os.Open(f)
if err != nil {
return 0, err
}
defer fr.Close()
r, err := gzip.NewReader(fr)
if err != nil {
return 0, err
}
return LineCount(r)
}
r, err := os.Open(f)
if err != nil {
return 0, err
}
defer r.Close()
return LineCount(r)
}
// ForEachLine higher order function that processes each line of text by callback function.
// The last non-empty line of input will be processed even if it has no newline.
func ForEachLine(br *bufio.Reader, callback func(string) error) error {
stop := false
for {
if stop {
break
}
line, err := br.ReadString('\n')
if err == io.EOF {
stop = true
} else if err != nil {
return err
}
line = strings.TrimSuffix(line, "\n")
if line == "" {
if !stop {
if err = callback(line); err != nil {
return err
}
}
continue
}
if err = callback(line); err != nil {
return err
}
}
return nil
}