From eb6b2a447a7e17f07b005554b1313e1a1419e544 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Sun, 21 Jan 2018 14:33:57 -0800 Subject: [PATCH] implement ReadFrom --- buffer.go | 29 ++++++++++++++++++++++++++++- buffer_test.go | 2 -- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/buffer.go b/buffer.go index 364722b..2e4645a 100644 --- a/buffer.go +++ b/buffer.go @@ -235,7 +235,34 @@ func (b *Buffer) WriteTo(w io.Writer) (int64, error) { return 0, nil } -// TODO: implement ReadFrom +// MinRead is the minimum slice size passed to a Read call by +// Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond +// what is required to hold the contents of r, ReadFrom will not grow the +// underlying buffer. +const MinRead = 512 + +// ReadFrom reads from the given reader into the buffer. +func (b *Buffer) ReadFrom(r io.Reader) (int64, error) { + n := int64(0) + for { + wOff := b.grow(MinRead) + // Use *entire* buffer. + b.buf = b.buf[:cap(b.buf)] + + read, err := r.Read(b.buf[wOff:]) + b.buf = b.buf[:wOff+read] + n += int64(read) + switch err { + case nil: + case io.EOF: + err = nil + fallthrough + default: + b.shrink() + return n, err + } + } +} // Read reads at most `len(buf)` bytes from the internal buffer into the given // buffer. diff --git a/buffer_test.go b/buffer_test.go index 05e28cf..900de2b 100644 --- a/buffer_test.go +++ b/buffer_test.go @@ -239,7 +239,6 @@ func TestNil(t *testing.T) { } } -/* func TestReadFrom(t *testing.T) { var buf Buffer for i := 3; i < 30; i += 3 { @@ -249,7 +248,6 @@ func TestReadFrom(t *testing.T) { empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data))) } } -*/ func TestWriteTo(t *testing.T) { var buf Buffer -- GitLab