Skip to content

Commit

Permalink
The Buffer type has two new methods: Available and AvailableBuffer. T…
Browse files Browse the repository at this point in the history
…hese may be used along with the Write method to append directly to the Buffer.
  • Loading branch information
zishang520 committed Sep 18, 2023
2 parents 9097323 + b2d81e7 commit c282647
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 2 additions & 0 deletions types/buffer-ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ type BufferInterface interface {
io.StringWriter
WriteRune(rune) (int, error)
Bytes() []byte
AvailableBuffer() []byte
fmt.Stringer
Len() int
Size() int64
Cap() int
Available() int
Truncate(int)
Reset()
Grow(int)
Expand Down
11 changes: 10 additions & 1 deletion types/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ const maxInt = int(^uint(0) >> 1)
// so immediate changes to the slice will affect the result of future reads.
func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }

// AvailableBuffer returns an empty buffer with b.Available() capacity.
// This buffer is intended to be appended to and
// passed to an immediately succeeding Write call.
// The buffer is only valid until the next write operation on b.
func (b *Buffer) AvailableBuffer() []byte { return b.buf[len(b.buf):] }

// String returns the contents of the unread portion of the buffer
// as a string. If the Buffer is a nil pointer, it returns "<nil>".
//
Expand All @@ -76,6 +82,9 @@ func (b *Buffer) Len() int { return len(b.buf) - b.off }
// total space allocated for the buffer's data.
func (b *Buffer) Cap() int { return cap(b.buf) }

// Available returns how many bytes are unused in the buffer.
func (b *Buffer) Available() int { return cap(b.buf) - len(b.buf) }

// Truncate discards all but the first n unread bytes from the buffer
// but continues to use the same allocated storage.
// It panics if n is negative or greater than the length of the buffer.
Expand All @@ -100,7 +109,7 @@ func (b *Buffer) Reset() {
b.lastRead = opInvalid
}

// tryGrowByReslice is a inlineable version of grow for the fast-case where the
// tryGrowByReslice is an inlineable version of grow for the fast-case where the
// internal buffer only needs to be resliced.
// It returns the index where bytes should be written and whether it succeeded.
func (b *Buffer) tryGrowByReslice(n int) (int, bool) {
Expand Down

0 comments on commit c282647

Please sign in to comment.