Commit 0566ab33 authored by Daniel Martí's avatar Daniel Martí

strings: add Builder.Cap

To report the capacity of the underlying buffer. The method mirrors
bytes.Buffer.Cap.

The method can be useful to know whether or not calling write or grow
methods will result in an allocation, or to know how much memory has
been allocated so far.

Fixes #26269.

Change-Id: I391db45ae825011566b594836991e28135369a78
Reviewed-on: https://go-review.googlesource.com/122835
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
parent b2e66f1a
......@@ -50,6 +50,11 @@ func (b *Builder) String() string {
// Len returns the number of accumulated bytes; b.Len() == len(b.String()).
func (b *Builder) Len() int { return len(b.buf) }
// Cap returns the capacity of the builder's underlying byte slice. It is the
// total space allocated for the string being built and includes any bytes
// already written.
func (b *Builder) Cap() int { return cap(b.buf) }
// Reset resets the Builder to be empty.
func (b *Builder) Reset() {
b.addr = nil
......
......@@ -20,6 +20,9 @@ func check(t *testing.T, b *Builder, want string) {
if n := b.Len(); n != len(got) {
t.Errorf("Len: got %d; but len(String()) is %d", n, len(got))
}
if n := b.Cap(); n < len(got) {
t.Errorf("Cap: got %d; but len(String()) is %d", n, len(got))
}
}
func TestBuilder(t *testing.T) {
......@@ -89,6 +92,9 @@ func TestBuilderGrow(t *testing.T) {
allocs := testing.AllocsPerRun(100, func() {
var b Builder
b.Grow(growLen) // should be only alloc, when growLen > 0
if b.Cap() < growLen {
t.Fatalf("growLen=%d: Cap() is lower than growLen", growLen)
}
b.Write(p)
if b.String() != string(p) {
t.Fatalf("growLen=%d: bad data written after Grow", growLen)
......@@ -226,6 +232,16 @@ func TestBuilderCopyPanic(t *testing.T) {
b.Len()
},
},
{
name: "Cap",
wantPanic: false,
fn: func() {
var a Builder
a.WriteByte('x')
b := a
b.Cap()
},
},
{
name: "Reset",
wantPanic: false,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment