forked from IBM/sarama
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
712b6bb
commit c9e4131
Showing
2 changed files
with
23 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,37 @@ | ||
package sarama | ||
|
||
import ( | ||
"sync" | ||
|
||
"github.com/klauspost/compress/zstd" | ||
) | ||
|
||
var zstdEncMap sync.Map | ||
|
||
var ( | ||
zstdDec, _ = zstd.NewReader(nil) | ||
zstdEnc, _ = zstd.NewWriter(nil, zstd.WithZeroFrames(true)) | ||
) | ||
|
||
func getEncoder(level int) *zstd.Encoder { | ||
if ret, ok := zstdEncMap.Load(level); ok { | ||
return ret.(*zstd.Encoder) | ||
} | ||
// It's possible to race and create multiple new writers. | ||
// Only one will survive GC after use. | ||
encoderLevel := zstd.SpeedDefault | ||
if level != CompressionLevelDefault { | ||
encoderLevel = zstd.EncoderLevelFromZstd(level) | ||
} | ||
zstdEnc, _ := zstd.NewWriter(nil, zstd.WithZeroFrames(true), | ||
zstd.WithEncoderLevel(encoderLevel)) | ||
zstdEncMap.Store(level, zstdEnc) | ||
return zstdEnc | ||
} | ||
|
||
func zstdDecompress(dst, src []byte) ([]byte, error) { | ||
return zstdDec.DecodeAll(src, dst) | ||
} | ||
|
||
func zstdCompress(dst, src []byte) ([]byte, error) { | ||
return zstdEnc.EncodeAll(src, dst), nil | ||
func zstdCompress(level int, dst, src []byte) ([]byte, error) { | ||
return getEncoder(level).EncodeAll(src, dst), nil | ||
} |