-
Notifications
You must be signed in to change notification settings - Fork 0
/
wfilter.go
94 lines (80 loc) · 2.04 KB
/
wfilter.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
90
91
92
93
94
// package wfilter provides facilities for adding filtering to io.Writer.
package wfilter
import (
"bytes"
"io"
)
type Prepend func(w io.Writer) (int, error)
// LinePrepender creates an io.Writer that prepends to each line by calling the
// given prepend function. Prepend can write whatever it wants. It should
// return the bytes written and any error encountered.
func LinePrepender(w io.Writer, prepend Prepend) io.Writer {
return &linePrepender{w, prepend, true}
}
type linePrepender struct {
io.Writer
prepend Prepend
prependNeeded bool
}
func (w *linePrepender) Write(buf []byte) (int, error) {
if w.prependNeeded {
_, err := w.prepend(w.Writer)
if err != nil {
return 0, err
}
w.prependNeeded = false
}
// Prepend before every newline in the buffer
totalN := 0
for {
i := bytes.IndexRune(buf, '\n') + 1
newlineFound := i > 0
newlineAtEnd := newlineFound && i == len(buf)
if !newlineFound {
break
} else if newlineAtEnd {
// Prepend will be needed at beginning of next write
w.prependNeeded = true
break
} else {
// Newline is somewhere before end
n, err := w.Writer.Write(buf[:i])
totalN += n
if err != nil {
return totalN, err
}
// Add prepend
_, err = w.prepend(w.Writer)
if err != nil {
return totalN, err
}
// Remove processed portion of buffer
buf = buf[i:]
}
}
// Write what's left of buf
n, err := w.Writer.Write(buf)
totalN += n
return totalN, err
}
// SimplePrepender creates an io.Writer that prepends by calling the given
// prepend function. Prepend can write whatever it wants. It should return
// the bytes written and any error encountered.
func SimplePrepender(w io.Writer, prepend Prepend) io.Writer {
return &simplePrepender{w, prepend}
}
type simplePrepender struct {
io.Writer
prepend Prepend
}
func (w *simplePrepender) Write(buf []byte) (int, error) {
written := 0
n, err := w.prepend(w.Writer)
written = written + n
if err != nil {
return written, err
}
n, err = w.Writer.Write(buf)
written = written + n
return written, err
}