Re-use zstd and zlib readers

This commit is contained in:
Caleb Gardner
2025-04-16 05:49:42 -05:00
parent 8a2556ea0d
commit 4c8c9f0b47
3 changed files with 43 additions and 14 deletions
+21 -6
View File
@@ -1,16 +1,31 @@
package decompress
import (
"sync"
"github.com/klauspost/compress/zstd"
)
type Zstd struct{}
type Zstd struct {
pool sync.Pool
}
func (z Zstd) Decompress(data []byte) ([]byte, error) {
rdr, err := zstd.NewReader(nil, zstd.WithDecoderLowmem(true), zstd.WithDecoderConcurrency(1))
if err != nil {
return nil, err
func NewZstd() *Zstd {
return &Zstd{
pool: sync.Pool{
New: func() any {
rdr, _ := zstd.NewReader(nil, zstd.WithDecoderLowmem(true), zstd.WithDecoderConcurrency(1))
return rdr
},
},
}
defer rdr.Close()
}
func (z *Zstd) Decompress(data []byte) ([]byte, error) {
rdr := z.pool.Get().(*zstd.Decoder)
defer func() {
rdr.Reset(nil)
z.pool.Put(rdr)
}()
return rdr.DecodeAll(data, nil)
}