Skip to content

Commit f2e3273

Browse files
authored
Add ability to create zstd compressor with compression level (#4203)
1 parent 441f441 commit f2e3273

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

utils/compression/compressor_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"runtime"
1010
"testing"
1111

12+
"github.com/DataDog/zstd"
1213
"github.com/stretchr/testify/require"
1314

1415
_ "embed"
@@ -149,6 +150,19 @@ func TestNewCompressorWithInvalidLimit(t *testing.T) {
149150
}
150151
}
151152

153+
func TestNewZstdCompressorWithLevel(t *testing.T) {
154+
compressor, err := NewZstdCompressorWithLevel(maxMessageSize, zstd.BestSpeed)
155+
require.NoError(t, err)
156+
157+
data := utils.RandomBytes(4096)
158+
compressed, err := compressor.Compress(data)
159+
require.NoError(t, err)
160+
161+
decompressed, err := compressor.Decompress(compressed)
162+
require.NoError(t, err)
163+
require.Equal(t, data, decompressed)
164+
}
165+
152166
func FuzzZstdCompressor(f *testing.F) {
153167
fuzzHelper(f, TypeZstd)
154168
}

utils/compression/zstd_compressor.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,28 +22,33 @@ var (
2222
)
2323

2424
func NewZstdCompressor(maxSize int64) (Compressor, error) {
25+
return NewZstdCompressorWithLevel(maxSize, zstd.DefaultCompression)
26+
}
27+
28+
func NewZstdCompressorWithLevel(maxSize int64, level int) (Compressor, error) {
2529
if maxSize == math.MaxInt64 {
2630
// "Decompress" creates "io.LimitReader" with max size + 1:
2731
// if the max size + 1 overflows, "io.LimitReader" reads nothing
2832
// returning 0 byte for the decompress call
2933
// require max size < math.MaxInt64 to prevent int64 overflows
3034
return nil, ErrInvalidMaxSizeCompressor
3135
}
32-
3336
return &zstdCompressor{
3437
maxSize: maxSize,
38+
level: level,
3539
}, nil
3640
}
3741

3842
type zstdCompressor struct {
3943
maxSize int64
44+
level int
4045
}
4146

4247
func (z *zstdCompressor) Compress(msg []byte) ([]byte, error) {
4348
if int64(len(msg)) > z.maxSize {
4449
return nil, fmt.Errorf("%w: (%d) > (%d)", ErrMsgTooLarge, len(msg), z.maxSize)
4550
}
46-
return zstd.Compress(nil, msg)
51+
return zstd.CompressLevel(nil, msg, z.level)
4752
}
4853

4954
func (z *zstdCompressor) Decompress(msg []byte) ([]byte, error) {

0 commit comments

Comments
 (0)