Codebase list golang-github-valyala-bytebufferpool-upstream / 18b5603
Added io.WriterTo implementation to ByteBuffer Aliaksandr Valialkin 7 years ago
2 changed file(s) with 34 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
00 package bytebufferpool
1
2 import "io"
13
24 // ByteBuffer provides byte buffer, which can be used for minimizing
35 // memory allocations.
1113 // B is a byte buffer to use in append-like workloads.
1214 // See example code for details.
1315 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
1422 }
1523
1624 // Bytes returns b.B, i.e. all the bytes accumulated in the buffer.
00 package bytebufferpool
11
22 import (
3 "bytes"
34 "fmt"
5 "io"
46 "testing"
57 "time"
68 )
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 }
733
834 func TestByteBufferGetPutSerial(t *testing.T) {
935 testByteBufferGetPut(t)