-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed
Labels
FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.The path to resolution is known, but the work has not been done.Proposal-Accepted
Milestone
Description
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.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.The path to resolution is known, but the work has not been done.Proposal-Accepted