-
Notifications
You must be signed in to change notification settings - Fork 343
/
compressor_zstd.go
80 lines (63 loc) · 1.91 KB
/
compressor_zstd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package compression
import (
"io"
"sync"
"github.com/klauspost/compress/zstd"
"github.com/pkg/errors"
"github.com/kopia/kopia/internal/iocopy"
)
func init() {
RegisterCompressor("zstd", newZstdCompressor(headerZstdDefault, zstd.SpeedDefault))
RegisterCompressor("zstd-fastest", newZstdCompressor(headerZstdFastest, zstd.SpeedFastest))
RegisterCompressor("zstd-better-compression", newZstdCompressor(headerZstdBetterCompression, zstd.SpeedBetterCompression))
RegisterCompressor("zstd-best-compression", newZstdCompressor(headerZstdBestCompression, zstd.SpeedBestCompression))
}
func newZstdCompressor(id HeaderID, level zstd.EncoderLevel) Compressor {
return &zstdCompressor{id, compressionHeader(id), sync.Pool{
New: func() interface{} {
w, err := zstd.NewWriter(io.Discard, zstd.WithEncoderLevel(level))
mustSucceed(err)
return w
},
}}
}
type zstdCompressor struct {
id HeaderID
header []byte
pool sync.Pool
}
func (c *zstdCompressor) HeaderID() HeaderID {
return c.id
}
func (c *zstdCompressor) Compress(output io.Writer, input io.Reader) error {
if _, err := output.Write(c.header); err != nil {
return errors.Wrap(err, "unable to write header")
}
// nolint:forcetypeassert
w := c.pool.Get().(*zstd.Encoder)
defer c.pool.Put(w)
w.Reset(output)
if err := iocopy.JustCopy(w, input); err != nil {
return errors.Wrap(err, "compression error")
}
if err := w.Close(); err != nil {
return errors.Wrap(err, "compression close error")
}
return nil
}
func (c *zstdCompressor) Decompress(output io.Writer, input io.Reader, withHeader bool) error {
if withHeader {
if err := verifyCompressionHeader(input, c.header); err != nil {
return err
}
}
r, err := zstd.NewReader(input)
if err != nil {
return errors.Wrap(err, "unable to open zstd stream")
}
defer r.Close()
if err := iocopy.JustCopy(output, r); err != nil {
return errors.Wrap(err, "decompression error")
}
return nil
}