gitee.com/h79/goutils@v1.22.10/common/compress/zstd.go (about) 1 package compress 2 3 import ( 4 "fmt" 5 "github.com/DataDog/zstd" 6 ) 7 8 // ZstdLevel compression level used by Zstd 9 const ZstdLevel = 1 // fastest 10 11 type noOp struct{} 12 13 func (n noOp) Name() string { return "Noop" } 14 func (n noOp) CompressBound(l int) int { return l } 15 func (n noOp) Compress(dst, src []byte) (int, error) { 16 if len(dst) < len(src) { 17 return 0, fmt.Errorf("buffer too short: %d < %d", len(dst), len(src)) 18 } 19 copy(dst, src) 20 return len(src), nil 21 } 22 func (n noOp) Decompress(dst, src []byte) (int, error) { 23 if len(dst) < len(src) { 24 return 0, fmt.Errorf("buffer too short: %d < %d", len(dst), len(src)) 25 } 26 copy(dst, src) 27 return len(src), nil 28 } 29 30 // ZStandard implements Compressor interface using zstd library 31 type ZStandard struct { 32 level int 33 } 34 35 // Name returns name of the algorithm Zstd 36 func (n ZStandard) Name() string { return "Zstd" } 37 38 // CompressBound max size of compressed data 39 func (n ZStandard) CompressBound(l int) int { return zstd.CompressBound(l) } 40 41 // Compress using Zstd 42 func (n ZStandard) Compress(dst, src []byte) (int, error) { 43 d, err := zstd.CompressLevel(dst, src, n.level) 44 if err != nil { 45 return 0, err 46 } 47 if len(d) > 0 && len(dst) > 0 && &d[0] != &dst[0] { 48 return 0, fmt.Errorf("buffer too short: %d < %d", cap(dst), cap(d)) 49 } 50 return len(d), err 51 } 52 53 // Decompress using Zstd 54 func (n ZStandard) Decompress(dst, src []byte) (int, error) { 55 d, err := zstd.Decompress(dst, src) 56 if err != nil { 57 return 0, err 58 } 59 if len(d) > 0 && len(dst) > 0 && &d[0] != &dst[0] { 60 return 0, fmt.Errorf("buffer too short: %d < %d", len(dst), len(d)) 61 } 62 return len(d), err 63 }