Added io.WriterTo implementation to ByteBuffer
Aliaksandr Valialkin
7 years ago
0 | 0 |
package bytebufferpool
|
|
1 |
|
|
2 |
import "io"
|
1 | 3 |
|
2 | 4 |
// ByteBuffer provides byte buffer, which can be used for minimizing
|
3 | 5 |
// memory allocations.
|
|
11 | 13 |
// B is a byte buffer to use in append-like workloads.
|
12 | 14 |
// See example code for details.
|
13 | 15 |
B []byte
|
|
16 |
}
|
|
17 |
|
|
18 |
// WriteTo implements io.WriterTo
|
|
19 |
func (b *ByteBuffer) WriteTo(w io.Writer) (int64, error) {
|
|
20 |
n, err := w.Write(b.B)
|
|
21 |
return int64(n), err
|
14 | 22 |
}
|
15 | 23 |
|
16 | 24 |
// Bytes returns b.B, i.e. all the bytes accumulated in the buffer.
|
0 | 0 |
package bytebufferpool
|
1 | 1 |
|
2 | 2 |
import (
|
|
3 |
"bytes"
|
3 | 4 |
"fmt"
|
|
5 |
"io"
|
4 | 6 |
"testing"
|
5 | 7 |
"time"
|
6 | 8 |
)
|
|
9 |
|
|
10 |
func TestByteBufferWriteTo(t *testing.T) {
|
|
11 |
expectedS := "foobarbaz"
|
|
12 |
var bb ByteBuffer
|
|
13 |
bb.WriteString(expectedS[:3])
|
|
14 |
bb.WriteString(expectedS[3:])
|
|
15 |
|
|
16 |
wt := (io.WriterTo)(&bb)
|
|
17 |
var w bytes.Buffer
|
|
18 |
for i := 0; i < 10; i++ {
|
|
19 |
n, err := wt.WriteTo(&w)
|
|
20 |
if n != int64(len(expectedS)) {
|
|
21 |
t.Fatalf("unexpected n returned from WriteTo: %d. Expecting %d", n, len(expectedS))
|
|
22 |
}
|
|
23 |
if err != nil {
|
|
24 |
t.Fatalf("unexpected error: %s", err)
|
|
25 |
}
|
|
26 |
s := string(w.Bytes())
|
|
27 |
if s != expectedS {
|
|
28 |
t.Fatalf("unexpected string written %q. Expecting %q", s, expectedS)
|
|
29 |
}
|
|
30 |
w.Reset()
|
|
31 |
}
|
|
32 |
}
|
7 | 33 |
|
8 | 34 |
func TestByteBufferGetPutSerial(t *testing.T) {
|
9 | 35 |
testByteBufferGetPut(t)
|