Skip to content

bytes: make Buffer.String avoid copy if possible #18990

@bradfitz

Description

@bradfitz

Years ago I filed #6714, hoping that it would one day be possible to construct a string efficiently without wasted allocations.

I hereby propose that we stop waiting and just do it explicitly with a new type in a new internal package.

package builder // import "internal/builder"

// String is like a bytes.Buffer but never allows its internal
// byte slice to escape. The zero value is usable.
type String struct {
     // ...
}

func (s *String) Len() int { ... }
func (s *String) Grow(n int) { ... }
func (s *String) WriteByte(b byte) { ... }
func (s *String) WriteString(s string) { ... }
func (s *String) Write(b []byte) { ... }
func (s *String) String() string { ... }

The (*String).String method would use unsafe to make a string header out of an internal []byte slice header.

The Write methods could even recycle old too-small []byte backing arrays as they grow.

There would be no Reset or Bytes or Truncate or Read methods. Nothing that could mutate the []byte once it was unsafely converted to a string.

The implementation would have to take care to use a new []byte backing array on any resize after an unsafe string was constructed.

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