aboutsummaryrefslogtreecommitdiff
path: root/src/bufio/bufio_test.go
diff options
context:
space:
mode:
authorJoe Tsai <joetsai@digital-static.net>2021-08-04 01:22:45 -0700
committerJoe Tsai <joetsai@digital-static.net>2021-09-12 01:06:53 +0000
commit0d8a4bfc962a606584be0a76ed708f86b44164c7 (patch)
tree11f8b6ff6d48e57bd0b9101fc0eeaccf554a0dff /src/bufio/bufio_test.go
parent23832ba2e2fb396cda1dacf3e8afcb38ec36dcba (diff)
downloadgo-0d8a4bfc962a606584be0a76ed708f86b44164c7.tar.xz
bufio: add Writer.AvailableBuffer
This adds a new Writer.AvailableBuffer method that returns an empty buffer with a possibly non-empty capacity for use with append-like APIs. The typical usage pattern is something like: b := bw.AvailableBuffer() b = appendValue(b, v) bw.Write(b) It allows logic combining append-like APIs with bufio.Writer to avoid needing to allocate and manage buffers themselves and allows the append-like APIs to directly write into the buffer for a bufio.Writer. Fixes #47527 Change-Id: I9cd169f3f8e8c7cd40818caf3daf1944c826fc66 Reviewed-on: https://go-review.googlesource.com/c/go/+/345569 Trust: Joe Tsai <joetsai@digital-static.net> Run-TryBot: Joe Tsai <joetsai@digital-static.net> TryBot-Result: Go Bot <gobot@golang.org> Reviewed-by: Ian Lance Taylor <iant@golang.org>
Diffstat (limited to 'src/bufio/bufio_test.go')
-rw-r--r--src/bufio/bufio_test.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/bufio/bufio_test.go b/src/bufio/bufio_test.go
index eb5136c9ea..04a810c206 100644
--- a/src/bufio/bufio_test.go
+++ b/src/bufio/bufio_test.go
@@ -10,6 +10,8 @@ import (
"errors"
"fmt"
"io"
+ "math/rand"
+ "strconv"
"strings"
"testing"
"testing/iotest"
@@ -608,6 +610,37 @@ func TestWriter(t *testing.T) {
}
}
+func TestWriterAppend(t *testing.T) {
+ got := new(bytes.Buffer)
+ var want []byte
+ rn := rand.New(rand.NewSource(0))
+ w := NewWriterSize(got, 64)
+ for i := 0; i < 100; i++ {
+ // Obtain a buffer to append to.
+ b := w.AvailableBuffer()
+ if w.Available() != cap(b) {
+ t.Fatalf("Available() = %v, want %v", w.Available(), cap(b))
+ }
+
+ // While not recommended, it is valid to append to a shifted buffer.
+ // This forces Write to copy the the input.
+ if rn.Intn(8) == 0 && cap(b) > 0 {
+ b = b[1:1:cap(b)]
+ }
+
+ // Append a random integer of varying width.
+ n := int64(rn.Intn(1 << rn.Intn(30)))
+ want = append(strconv.AppendInt(want, n, 10), ' ')
+ b = append(strconv.AppendInt(b, n, 10), ' ')
+ w.Write(b)
+ }
+ w.Flush()
+
+ if !bytes.Equal(got.Bytes(), want) {
+ t.Errorf("output mismatch:\ngot %s\nwant %s", got.Bytes(), want)
+ }
+}
+
// Check that write errors are returned properly.
type errorWriterTest struct {