-
Notifications
You must be signed in to change notification settings - Fork 1
/
io.go
89 lines (76 loc) · 1.75 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
81
82
83
84
85
86
87
88
89
package goutils
import (
"bufio"
"bytes"
"fmt"
"io"
)
// ReadBytes reads n bytes from reader.
func ReadBytes(reader io.Reader, n int) ([]byte, error) {
if reader == nil || n <= 0 {
return nil, fmt.Errorf("invalid args (%v, %v)", reader, n)
}
buf := make([]byte, n)
pos := 0
for {
m, err := reader.Read(buf[pos:])
if err != nil {
if err == io.EOF {
pos += m
if pos < n {
return buf[:pos], err
}
return buf, nil
}
return nil, err
}
pos += m
if pos >= n {
return buf, nil
}
}
}
// ForeachLine reads string from reader line-by-line.
func ForeachLine(reader io.Reader, fun func(line string) error) error {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
err := fun(scanner.Text())
if err != nil {
return err
}
}
return scanner.Err()
}
// Transformer transforms bytes.
type Transformer interface {
Transform([]byte) ([]byte, error)
}
// CombineTransformer combines multi transformers.
type CombineTransformer []Transformer
func (ts CombineTransformer) Transform(data []byte) ([]byte, error) {
var err error
for i, t := range ts {
if t == nil {
continue
}
data, err = t.Transform(data)
if err != nil {
return nil, fmt.Errorf("perform transformer at index %d failed, %v", i, err)
}
}
return data, nil
}
// The TransformFunc type is an adapter to allow the use of
// ordinary functions as Transformer.
type TransformFunc func([]byte) ([]byte, error)
func (f TransformFunc) Transform(data []byte) ([]byte, error) {
return f(data)
}
// StringReplacer replaces string data.
type StringReplacer map[string]string
func (r StringReplacer) Transform(data []byte) ([]byte, error) {
for old, new := range r {
data = bytes.ReplaceAll(data, []byte(old), []byte(new))
}
return data, nil
}