From 62dfa43101ce0abe5c919b4c996a9ba157e6a5e0 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 23 Apr 2024 15:42:22 -0700 Subject: bytes: add test to ensure shallow copy of NewBuffer does not allocate At present, there is no API to reset the underlying []byte of an existing Buffer struct, except to shallow copy the entire Buffer struct. Updates #67004 Change-Id: I08998f7a95ae5bde0897d86247d47f23cd784583 Reviewed-on: https://go-review.googlesource.com/c/go/+/581297 Auto-Submit: Joseph Tsai Reviewed-by: Joedian Reid TryBot-Result: Gopher Robot Reviewed-by: Keith Randall Run-TryBot: Joseph Tsai Reviewed-by: Keith Randall LUCI-TryBot-Result: Go LUCI --- src/bytes/buffer_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/bytes/buffer_test.go b/src/bytes/buffer_test.go index 845e5e2209..322e7367c7 100644 --- a/src/bytes/buffer_test.go +++ b/src/bytes/buffer_test.go @@ -94,6 +94,21 @@ func TestNewBuffer(t *testing.T) { check(t, "NewBuffer", buf, testString) } +var buf Buffer + +// Calling NewBuffer and immediately shallow copying the Buffer struct +// should not result in any allocations. +// This can be used to reset the underlying []byte of an existing Buffer. +func TestNewBufferShallow(t *testing.T) { + n := testing.AllocsPerRun(1000, func() { + buf = *NewBuffer(testBytes) + }) + if n > 0 { + t.Errorf("allocations occurred while shallow copying") + } + check(t, "NewBuffer", &buf, testString) +} + func TestNewBufferString(t *testing.T) { buf := NewBufferString(testString) check(t, "NewBufferString", buf, testString) -- cgit v1.2.3-54-g00ecf