Skip to content
Merged
Show file tree
Hide file tree
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
7 changes: 5 additions & 2 deletions zstd.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const (
// decompressed, err := zstd.Decompress(dst, src)
decompressSizeBufferLimit = 1000 * 1000

zstdFrameHeaderSizeMax = 18 // From zstd.h. Since it's experimental API, hardcoding it
zstdFrameHeaderSizeMin = 2 // From zstd.h. Since it's experimental API, hardcoding it
)

// CompressBound returns the worst case size needed for a destination buffer,
Expand Down Expand Up @@ -67,11 +67,14 @@ func decompressSizeHint(src []byte) int {
}

hint := upperBound
if len(src) >= zstdFrameHeaderSizeMax {
if len(src) >= zstdFrameHeaderSizeMin {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not check the upper bound as well?

len(src) >= zstdFrameHeaderSizeMin && len(src) <= zstdFrameHeaderSizeMax

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what you mean ? That check if just to make sure the header is in the payload but src will 99% of the time be bigger than zstdFrameHeaderSizeMax (and that's fine)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 sorry I thought that src would only be the header, I didn't realize it was the full payload.

hint = int(C.ZSTD_getFrameContentSize(unsafe.Pointer(&src[0]), C.size_t(len(src))))
if hint < 0 { // On error, just use upperBound
hint = upperBound
}
if hint == 0 { // When compressing the empty slice, we need an output of at least 1 to pass down to the C lib
hint = 1
}
}

// Take the minimum of both
Expand Down
19 changes: 19 additions & 0 deletions zstd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,25 @@ func TestBadPayloadZipBomb(t *testing.T) {
}
}

func TestSmallPayload(t *testing.T) {
// Test that we can compress really small payloads and this doesn't generate a huge output buffer
compressed, err := Compress(nil, []byte("a"))
if err != nil {
t.Fatalf("failed to compress: %s", err)
}

preAllocated := make([]byte, 1, 64) // Don't use more than that
decompressed, err := Decompress(preAllocated, compressed)
if err != nil {
t.Fatalf("failed to compress: %s", err)
}

if &(preAllocated[0]) != &(decompressed[0]) { // They should point to the same spot (no realloc)
t.Fatal("Compression buffer was changed")
}

}

func BenchmarkCompression(b *testing.B) {
if raw == nil {
b.Fatal(ErrNoPayloadEnv)
Expand Down