Skip to content

Commit

Permalink
fix: now working with too small buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
4kills committed Jan 19, 2024
1 parent 7ab1faa commit 5717b50
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 21 deletions.
15 changes: 2 additions & 13 deletions reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
}
Expand Down
42 changes: 34 additions & 8 deletions reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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())
}

0 comments on commit 5717b50

Please sign in to comment.