github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/compress/zstd/zstd_nocgo.go (about) 1 // +build !cgo 2 3 package zstd 4 5 import ( 6 "bytes" 7 "io" 8 9 nocgozstd "github.com/klauspost/compress/zstd" 10 ) 11 12 func CompressLevel(scratch []byte, in []byte, level int) ([]byte, error) { 13 if level < 0 { 14 level = 5 // 5 is the default compression const in cgo zstd 15 } 16 wBuf := bytes.NewBuffer(scratch[:0]) 17 w, err := nocgozstd.NewWriter(wBuf, 18 nocgozstd.WithEncoderLevel(nocgozstd.EncoderLevelFromZstd(level))) 19 if err != nil { 20 return nil, err 21 } 22 rBuf := bytes.NewReader(in) 23 _, err = io.Copy(w, rBuf) 24 if err != nil { 25 return nil, err 26 } 27 if err := w.Close(); err != nil { 28 return nil, err 29 } 30 return wBuf.Bytes(), nil 31 } 32 33 func Decompress(scratch []byte, in []byte) ([]byte, error) { 34 rBuf := bytes.NewReader(in) 35 r, err := nocgozstd.NewReader(rBuf) 36 if err != nil { 37 return nil, err 38 } 39 40 wBuf := bytes.NewBuffer(scratch[:0]) 41 if _, err = io.Copy(wBuf, r); err != nil { 42 return nil, err 43 } 44 r.Close() 45 return wBuf.Bytes(), nil 46 } 47 48 type readerWrapper struct { 49 *nocgozstd.Decoder 50 } 51 52 func (r *readerWrapper) Close() error { 53 r.Decoder.Close() 54 return nil 55 } 56 57 func NewReader(r io.Reader) (io.ReadCloser, error) { 58 zr, err := nocgozstd.NewReader(r) 59 if err != nil { 60 return nil, err 61 } 62 return &readerWrapper{zr}, nil 63 } 64 65 func NewWriter(w io.Writer) (io.WriteCloser, error) { 66 return nocgozstd.NewWriter(w) 67 }