Skip to content

Commit f7fe1cc

Browse files
committed
Add new CountingWriter struct
1 parent 86e5161 commit f7fe1cc

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed
Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,24 @@
11
package readwriter
22

3-
import "io"
3+
import (
4+
"io"
5+
)
46

57
type ReadWriter struct {
68
Out io.Writer
79
In io.Reader
810
ErrOut io.Writer
911
}
12+
13+
// CountingWriter wraps an io.Writer and counts all the writes. Accessing
14+
// the count N is not thread-safe.
15+
type CountingWriter struct {
16+
W io.Writer
17+
N int64
18+
}
19+
20+
func (cw *CountingWriter) Write(p []byte) (int, error) {
21+
n, err := cw.W.Write(p)
22+
cw.N += int64(n)
23+
return n, err
24+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package readwriter
2+
3+
import (
4+
"bytes"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestCountingWriter_Write(t *testing.T) {
11+
testString := []byte("test string")
12+
buffer := &bytes.Buffer{}
13+
14+
cw := &CountingWriter{
15+
W: buffer,
16+
}
17+
18+
n, err := cw.Write(testString)
19+
20+
require.NoError(t, err)
21+
require.Equal(t, 11, n)
22+
require.Equal(t, int64(11), cw.N)
23+
24+
cw.Write(testString)
25+
require.Equal(t, int64(22), cw.N)
26+
}

0 commit comments

Comments
 (0)