2019-07-23 18:26:39 +02: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
|
|
|
|
av atomic.Value
|
|
|
|
)
|
|
|
|
|
|
|
|
type registry map[int]*zstd.Encoder
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
r := make(registry)
|
|
|
|
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 {
|
|
|
|
r := av.Load().(registry)
|
2019-07-24 18:15:33 +02:00
|
|
|
e := r[compressionLevel]
|
|
|
|
if e != nil {
|
2019-07-23 18:26:39 +02:00
|
|
|
return e
|
|
|
|
}
|
|
|
|
|
|
|
|
mu.Lock()
|
2019-07-24 18:15:33 +02:00
|
|
|
// Create the encoder under lock in order to prevent from wasted work
|
|
|
|
// when concurrent goroutines create encoder for the same compressionLevel.
|
2019-07-23 18:26:39 +02:00
|
|
|
r1 := av.Load().(registry)
|
2019-12-23 17:04:57 +01:00
|
|
|
if e = r1[compressionLevel]; e == nil {
|
|
|
|
e = newEncoder(compressionLevel)
|
|
|
|
r2 := make(registry)
|
|
|
|
for k, v := range r1 {
|
|
|
|
r2[k] = v
|
|
|
|
}
|
|
|
|
r2[compressionLevel] = e
|
|
|
|
av.Store(r2)
|
2019-07-23 18:26:39 +02:00
|
|
|
}
|
|
|
|
mu.Unlock()
|
|
|
|
|
|
|
|
return e
|
|
|
|
}
|
2019-07-24 18:15:33 +02: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
|
|
|
|
}
|