From b2d81e7ca72f4070fb4c2c10101ee06f1bd7eeae Mon Sep 17 00:00:00 2001 From: luoyy Date: Mon, 21 Aug 2023 23:31:51 +0800 Subject: [PATCH] The Buffer type has two new methods: Available and AvailableBuffer. These may be used along with the Write method to append directly to the Buffer. --- types/buffer-ext.go | 2 ++ types/buffer.go | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/types/buffer-ext.go b/types/buffer-ext.go index d0b6219..2d5cc24 100644 --- a/types/buffer-ext.go +++ b/types/buffer-ext.go @@ -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) diff --git a/types/buffer.go b/types/buffer.go index e9c8087..46c8c42 100644 --- a/types/buffer.go +++ b/types/buffer.go @@ -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 "". // @@ -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. @@ -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) {