Skip to content

strings: add Builder.Cap method #26269

@mvdan

Description

@mvdan

This would mirror bytes.Buffer.Cap, which returns the capacity of the underlying []byte.

In particular, I need access to the capacity to calculate if a number of bytes will fit in the Builder without an allocation. That would look like:

func canFitBytes(b *strings.Builder, n int) bool {
    remaining := b.Cap() - b.Len()
    return remaining >= n
}

One possible use case is to control how the allocations happen. For example, I'd like to "batch" []byte to string allocations, to amortize their cost until the compiler gets smart enough to remove the allocs when possible.

My code could look like:

// amortizedString is like string(p), but for small strings, allocations are batched via a strings.Builder.
func amortizedString(b *strings.Builder, p []byte) string {
    if len(p) >= 2048 {
        return string(p)
    }
    if !canFitBytes(b, len(p)) {
        b.Reset()
        b.Grow(2048)
    }
    start := b.Len()
    b.Write(p)
    return b.String()[start:]
}

As far as I can tell, writing such a function is not simple without a Cap method. And adding such a method shouldn't add any problems, other than adding to the API. Unless there is a particular reason why the method was left out that I'm not aware of.

/cc @cespare @bradfitz @ianlancetaylor

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions