-
Notifications
You must be signed in to change notification settings - Fork 0
/
gz.go
84 lines (65 loc) · 1.59 KB
/
gz.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
81
82
83
84
package compressor
import (
"bytes"
"compress/gzip"
"io"
"strings"
"github.com/klauspost/pgzip"
)
// Gz facilitates gzip compression.
type Gz struct {
// Gzip compression level.
// If 0, DefaultCompression is assumed, not no compression.
CompressionLevel int
// Use a fast parallel Gzip implementation.
// This is effective only for large threads (about 1 MB or more).
Multithreaded bool
}
// magic number at the beginning of gzip files
var gzHeader = []byte{0x1f, 0x8b}
func init() {
RegisterFormat(Gz{})
}
func (Gz) Name() string {
return ".gz"
}
func (gz Gz) Match(filename string, stream io.Reader) (MatchResult, error) {
var mr MatchResult
// match filename
if strings.Contains(strings.ToLower(filename), gz.Name()) {
mr.ByName = true
}
// match file header
buf, err := readAtMost(stream, len(gzHeader))
if err != nil {
return mr, err
}
mr.ByStream = bytes.Equal(buf, gzHeader)
return mr, nil
}
func (gz Gz) OpenWriter(w io.Writer) (io.WriteCloser, error) {
var wc io.WriteCloser
var err error
// The default compression level is 0, not no compression.
// The lack of compression in the gzipped file makes no sense in this project.
level := gz.CompressionLevel
if level == 0 {
level = gzip.DefaultCompression
}
if gz.Multithreaded {
wc, err = pgzip.NewWriterLevel(w, level)
} else {
wc, err = gzip.NewWriterLevel(w, level)
}
return wc, err
}
func (gz Gz) OpenReader(r io.Reader) (io.ReadCloser, error) {
var rc io.ReadCloser
var err error
if gz.Multithreaded {
rc, err = pgzip.NewReader(r)
} else {
rc, err = gzip.NewReader(r)
}
return rc, err
}