2021-07-26 11:09:12 +00:00
|
|
|
//go:build !cgo
|
2019-07-23 16:26:39 +00:00
|
|
|
// +build !cgo
|
|
|
|
|
|
|
|
package zstd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
|
|
|
|
"github.com/klauspost/compress/zstd"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
decoder *zstd.Decoder
|
|
|
|
|
|
|
|
mu sync.Mutex
|
|
|
|
|
2023-07-21 03:55:27 +00:00
|
|
|
// do not use atomic.Pointer, since the stored map there is already a pointer type.
|
|
|
|
av atomic.Value
|
|
|
|
)
|
2019-07-23 16:26:39 +00:00
|
|
|
|
|
|
|
func init() {
|
2023-07-21 03:55:27 +00:00
|
|
|
r := make(map[int]*zstd.Encoder)
|
2019-07-23 16:26:39 +00:00
|
|
|
av.Store(r)
|
|
|
|
|
|
|
|
var err error
|
|
|
|
decoder, err = zstd.NewReader(nil)
|
|
|
|
if err != nil {
|
|
|
|
logger.Panicf("BUG: failed to create ZSTD reader: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decompress appends decompressed src to dst and returns the result.
|
|
|
|
func Decompress(dst, src []byte) ([]byte, error) {
|
|
|
|
return decoder.DecodeAll(src, dst)
|
|
|
|
}
|
|
|
|
|
|
|
|
// CompressLevel appends compressed src to dst and returns the result.
|
|
|
|
//
|
|
|
|
// The given compressionLevel is used for the compression.
|
|
|
|
func CompressLevel(dst, src []byte, compressionLevel int) []byte {
|
|
|
|
e := getEncoder(compressionLevel)
|
|
|
|
return e.EncodeAll(src, dst)
|
|
|
|
}
|
|
|
|
|
|
|
|
func getEncoder(compressionLevel int) *zstd.Encoder {
|
2023-07-21 03:55:27 +00:00
|
|
|
r := av.Load().(map[int]*zstd.Encoder)
|
2019-07-24 16:15:33 +00:00
|
|
|
e := r[compressionLevel]
|
|
|
|
if e != nil {
|
2019-07-23 16:26:39 +00:00
|
|
|
return e
|
|
|
|
}
|
|
|
|
|
|
|
|
mu.Lock()
|
2019-07-24 16:15:33 +00:00
|
|
|
// Create the encoder under lock in order to prevent from wasted work
|
|
|
|
// when concurrent goroutines create encoder for the same compressionLevel.
|
2023-07-21 03:55:27 +00:00
|
|
|
r1 := av.Load().(map[int]*zstd.Encoder)
|
2019-12-23 16:04:57 +00:00
|
|
|
if e = r1[compressionLevel]; e == nil {
|
|
|
|
e = newEncoder(compressionLevel)
|
2023-07-21 03:55:27 +00:00
|
|
|
r2 := make(map[int]*zstd.Encoder)
|
2019-12-23 16:04:57 +00:00
|
|
|
for k, v := range r1 {
|
|
|
|
r2[k] = v
|
|
|
|
}
|
|
|
|
r2[compressionLevel] = e
|
|
|
|
av.Store(r2)
|
2019-07-23 16:26:39 +00:00
|
|
|
}
|
|
|
|
mu.Unlock()
|
|
|
|
|
|
|
|
return e
|
|
|
|
}
|
2019-07-24 16:15:33 +00:00
|
|
|
|
|
|
|
func newEncoder(compressionLevel int) *zstd.Encoder {
|
|
|
|
level := zstd.EncoderLevelFromZstd(compressionLevel)
|
|
|
|
e, err := zstd.NewWriter(nil,
|
|
|
|
zstd.WithEncoderCRC(false), // Disable CRC for performance reasons.
|
|
|
|
zstd.WithEncoderLevel(level))
|
|
|
|
if err != nil {
|
|
|
|
logger.Panicf("BUG: failed to create ZSTD writer: %s", err)
|
|
|
|
}
|
|
|
|
return e
|
|
|
|
}
|