Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add BytesCopy and StringCopy #265

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions fflib/v1/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ type bytesReader interface {
String() string
}

type bytesCopyReader interface {
BytesCopy() []byte
StringCopy() string
}

type runeWriter interface {
WriteRune(r rune) (n int, err error)
}
Expand Down Expand Up @@ -59,6 +64,7 @@ type EncodingBuffer interface {
grower
rewinder
encoder
bytesCopyReader
}

type DecodingBuffer interface {
Expand All @@ -70,6 +76,7 @@ type DecodingBuffer interface {
grower
bytesReader
lener
bytesCopyReader
}

// A Buffer is a variable-sized buffer of bytes with Read and Write methods.
Expand All @@ -91,6 +98,13 @@ var ErrTooLarge = errors.New("fflib.v1.Buffer: too large")
// are no intervening method calls on the Buffer.
func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }

// BytesCopy returns a copy of slice of the contents of the unread portion of the buffer
func (b *Buffer) BytesCopy() []byte {
bs := make([]byte, b.Len())
copy(bs, b.buf[b.off:])
return bs
}

// String returns the contents of the unread portion of the buffer
// as a string. If the Buffer is a nil pointer, it returns "<nil>".
func (b *Buffer) String() string {
Expand All @@ -101,6 +115,14 @@ func (b *Buffer) String() string {
return string(b.buf[b.off:])
}

// StringCopy returns the copy of contents of the unread portion
func (b *Buffer) StringCopy() string {
if b == nil {
return "<nil>"
}
return string(b.BytesCopy())
}

// Len returns the number of bytes of the unread portion of the buffer;
// b.Len() == len(b.Bytes()).
func (b *Buffer) Len() int { return len(b.buf) - b.off }
Expand Down