-
Notifications
You must be signed in to change notification settings - Fork 336
/
compressor_pgzip.go
80 lines (63 loc) · 1.81 KB
/
compressor_pgzip.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 (
"bytes"
"io"
"sync"
"github.com/klauspost/pgzip"
"github.com/pkg/errors"
"github.com/kopia/kopia/internal/iocopy"
)
func init() {
RegisterCompressor("pgzip", newpgzipCompressor(headerPgzipDefault, pgzip.DefaultCompression))
RegisterCompressor("pgzip-best-speed", newpgzipCompressor(headerPgzipBestSpeed, pgzip.BestSpeed))
RegisterCompressor("pgzip-best-compression", newpgzipCompressor(headerPgzipBestCompression, pgzip.BestCompression))
}
func newpgzipCompressor(id HeaderID, level int) Compressor {
return &pgzipCompressor{id, compressionHeader(id), sync.Pool{
New: func() interface{} {
w, err := pgzip.NewWriterLevel(bytes.NewBuffer(nil), level)
mustSucceed(err)
return w
},
}}
}
type pgzipCompressor struct {
id HeaderID
header []byte
pool sync.Pool
}
func (c *pgzipCompressor) HeaderID() HeaderID {
return c.id
}
func (c *pgzipCompressor) 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().(*pgzip.Writer)
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 *pgzipCompressor) Decompress(output io.Writer, input io.Reader, withHeader bool) error {
if withHeader {
if err := verifyCompressionHeader(input, c.header); err != nil {
return err
}
}
r, err := pgzip.NewReader(input)
if err != nil {
return errors.Wrap(err, "unable to open gzip stream")
}
defer r.Close() //nolint:errcheck
if err := iocopy.JustCopy(output, r); err != nil {
return errors.Wrap(err, "decompression error")
}
return nil
}