Skip to content

Commit

Permalink
Fix handling of short streams
Browse files Browse the repository at this point in the history
Before this change, on streams shorter than 6 bytes, we would present up
to 6 bytes of garbage at the start of the buffer.

With this change in place, we now present exactly what we read.

Introduced in e7ecaa2. Fixes #263.
  • Loading branch information
walles committed Jan 12, 2025
1 parent 523c426 commit b063ab0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 2 additions & 1 deletion m/zopen.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,15 @@ func ZOpen(filename string) (io.ReadCloser, string, error) {
func ZReader(input io.Reader) (io.Reader, error) {
// Read the first 6 bytes to determine the compression type
firstBytes := make([]byte, 6)
_, err := input.Read(firstBytes)
count, err := input.Read(firstBytes)
if err != nil {
if err == io.EOF {
// Stream was empty
return input, nil
}
return nil, fmt.Errorf("failed to read stream: %w", err)
}
firstBytes = firstBytes[:count]

// Reset input reader to start of stream
input = io.MultiReader(bytes.NewReader(firstBytes), input)
Expand Down
36 changes: 36 additions & 0 deletions m/zopen_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package m

import (
"bytes"
"io"
"testing"

"gotest.tools/v3/assert"
)

// Test that ZReader works with an empty stream
func TestZReaderEmpty(t *testing.T) {
bytesReader := bytes.NewReader([]byte{})

zReader, err := ZReader(bytesReader)
assert.NilError(t, err)

all, err := io.ReadAll(zReader)
assert.NilError(t, err)

assert.Equal(t, 0, len(all))
}

// Test that ZReader works with a one-byte stream
func TestZReaderOneByte(t *testing.T) {
bytesReader := bytes.NewReader([]byte{42})

zReader, err := ZReader(bytesReader)
assert.NilError(t, err)

all, err := io.ReadAll(zReader)
assert.NilError(t, err)

assert.Equal(t, 1, len(all))
assert.Equal(t, byte(42), all[0])
}

0 comments on commit b063ab0

Please sign in to comment.