-
Notifications
You must be signed in to change notification settings - Fork 4
/
tee.go
70 lines (55 loc) · 1.34 KB
/
tee.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
package iokit
import (
"io"
)
func NewTeeWriter(main, copy io.Writer) io.Writer {
return &TeeWriter{main, teeTemplate{copy, 0}}
}
func NewTeeWriterWithSkip(main, copy io.Writer, zeroLeadingBytes int) io.Writer {
return &TeeWriter{main, teeTemplate{copy, zeroLeadingBytes}}
}
func NewTeeReader(main io.Reader, copy io.Writer) io.Reader {
return &TeeReader{main, teeTemplate{copy, 0}}
}
func NewTeeReaderWithSkip(main io.Reader, copy io.Writer, skipLeadingBytes int) io.Reader {
return &TeeReader{main, teeTemplate{copy, skipLeadingBytes}}
}
type teeTemplate struct {
CopyTo io.Writer
CopySkip int
}
func (w *teeTemplate) teeWrite(n int, b []byte) {
switch {
case w.CopyTo == nil:
return
case w.CopySkip <= 0:
_, _ = w.CopyTo.Write(b[:n])
case w.CopySkip >= n:
w.CopySkip -= n
default:
_, _ = w.CopyTo.Write(b[w.CopySkip:n])
w.CopySkip = 0
}
}
/***********************************************/
var _ io.Writer = &TeeWriter{}
type TeeWriter struct {
W io.Writer
teeTemplate
}
func (w *TeeWriter) Write(b []byte) (n int, err error) {
n, err = w.W.Write(b)
w.teeWrite(n, b)
return n, err
}
/***********************************************/
var _ io.Reader = &TeeReader{}
type TeeReader struct {
R io.Reader
teeTemplate
}
func (w *TeeReader) Read(b []byte) (n int, err error) {
n, err = w.R.Read(b)
w.teeWrite(n, b)
return n, err
}