From 5717b50f2f80e581c90dcca854f42eff0a3afbcd Mon Sep 17 00:00:00 2001 From: 4kills Date: Fri, 19 Jan 2024 09:46:51 +0100 Subject: [PATCH] fix: now working with too small buffers --- reader.go | 15 ++------------- reader_test.go | 42 ++++++++++++++++++++++++++++++++++-------- 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/reader.go b/reader.go index d15b280..92809f8 100644 --- a/reader.go +++ b/reader.go @@ -60,18 +60,7 @@ func (r *Reader) Read(p []byte) (int, error) { } if r.outBuffer.Len() != 0 { - min := len(p) - if len(p) < r.outBuffer.Len() { - min = r.outBuffer.Len() - } - copy(p, r.outBuffer.Bytes()[:min]) - r.outBuffer.Next(min) - - var err error - if r.outBuffer.Len() == 0 && r.eof { - err = io.EOF - } - return min, err + return r.outBuffer.Read(p) } n, err := r.r.Read(p) @@ -87,7 +76,7 @@ func (r *Reader) Read(p []byte) (int, error) { } r.inBuffer.Next(processed) - if r.eof && len(out) <= len(p){ + if r.eof && len(out) <= len(p) { copy(p, out) return len(out), io.EOF } diff --git a/reader_test.go b/reader_test.go index ef05c89..da14d06 100644 --- a/reader_test.go +++ b/reader_test.go @@ -29,7 +29,7 @@ func TestReadBytes(t *testing.T) { sliceEquals(t, longString, act) } -func TestRead_SufficientBuffer(t *testing.T) { +func initTestRead(t *testing.T, bufferSize int) (*bytes.Buffer, *zlib.Writer, *Reader, func(r *Reader) error) { b := &bytes.Buffer{} out := &bytes.Buffer{} w := zlib.NewWriter(b) @@ -39,27 +39,53 @@ func TestRead_SufficientBuffer(t *testing.T) { t.Error(err) t.FailNow() } - defer r.Close() - read := func() { - p := make([]byte, 1e+4) + read := func(r *Reader) error { + p := make([]byte, bufferSize) n, err := r.Read(p) if err != nil && err != io.EOF { t.Error(err) t.Error(n) + t.FailNow() } out.Write(p[:n]) + return err // io.EOF or nil } - _, err = w.Write(shortString) + return out, w, r, read +} + +func TestRead_SufficientBuffer(t *testing.T) { + out, w, r, read := initTestRead(t, 1e+4) + defer r.Close() + + w.Write(shortString) w.Flush() - read() + read(r) - _, err = w.Write(shortString) + w.Write(shortString) w.Close() - read() + read(r) + + sliceEquals(t, append(shortString, shortString...), out.Bytes()) +} + +func TestRead_SmallBuffer(t *testing.T) { + out, w, r, read := initTestRead(t, 1) + defer r.Close() + + w.Write(shortString) + w.Write(shortString) + w.Close() + + for { + err := read(r) + if err == io.EOF { + break + } + } sliceEquals(t, append(shortString, shortString...), out.Bytes()) }