forked from mholt/archiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zstd.go
64 lines (50 loc) · 1.28 KB
/
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
package archiver
import (
"bytes"
"io"
"strings"
"github.com/klauspost/compress/zstd"
)
func init() {
RegisterFormat(Zstd{})
}
// Zstd facilitates Zstandard compression.
type Zstd struct {
EncoderOptions []zstd.EOption
DecoderOptions []zstd.DOption
}
func (Zstd) Name() string { return ".zst" }
func (zs Zstd) Match(filename string, stream io.Reader) (MatchResult, error) {
var mr MatchResult
// match filename
if strings.Contains(strings.ToLower(filename), zs.Name()) {
mr.ByName = true
}
// match file header
buf, err := readAtMost(stream, len(zstdHeader))
if err != nil {
return mr, err
}
mr.ByStream = bytes.Equal(buf, zstdHeader)
return mr, nil
}
func (zs Zstd) OpenWriter(w io.Writer) (io.WriteCloser, error) {
return zstd.NewWriter(w, zs.EncoderOptions...)
}
func (zs Zstd) OpenReader(r io.Reader) (io.ReadCloser, error) {
zr, err := zstd.NewReader(r, zs.DecoderOptions...)
if err != nil {
return nil, err
}
return errorCloser{zr}, nil
}
type errorCloser struct {
*zstd.Decoder
}
func (ec errorCloser) Close() error {
ec.Decoder.Close()
return nil
}
// magic number at the beginning of Zstandard files
// https://github.com/facebook/zstd/blob/6211bfee5ec24dc825c11751c33aa31d618b5f10/doc/zstd_compression_format.md
var zstdHeader = []byte{0x28, 0xb5, 0x2f, 0xfd}