Skip to content

bytes: add Buffer.Available and Buffer.AvailableBuffer #53685

@sirkon

Description

@sirkon

Hi!

I propose to introduce a new method to bytes.Buffer:

// Extend grows buffer by n bytes, moves write position at the end of 
// just grown data and return a part of buffer what extended the
// previous content.
func (b *Buffer) Extend(n int) []byte {
    b.Grow(n)
    l := len(b.buf)
    b.buf = b.buf[:l + n]
    return b.buf[l:]
}

Rationale.

Grow combined with Write is nice, but some APIs, binary.PutUvarint for instance, works with slices of bytes. This means memory copying will be needed in order to write uvarint-encoded data. Lots of memory copies in my case where I have manual serialization for some data structures.

I guess this method would be handy in cases like mine, where I would:

  1. Extend buffer by the length of the serialized data.
  2. Will serialize right into the returned slice.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions