-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
106 lines (84 loc) · 1.84 KB
/
compress.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package encoding
import (
"bytes"
"fmt"
"io/ioutil"
"github.com/klauspost/compress/gzip"
"github.com/klauspost/compress/s2"
)
const (
s2Compression = 0x1
gzipCompression = 0x2
)
type DefaultCompressor struct {
algorithm int
}
//
// gzip compression algorithm
//
func (c *DefaultCompressor) gzipCompress(data []byte) ([]byte, error) {
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write(data)
err := w.Close()
return b.Bytes(), err
}
func (c *DefaultCompressor) gzipDecompress(data []byte) ([]byte, error) {
b := bytes.NewReader(data)
r, err := gzip.NewReader(b)
if err != nil {
return data, err
}
defer r.Close()
return ioutil.ReadAll(r)
}
//
// s2 compression algorithm
//
func (c *DefaultCompressor) s2Compress(data []byte) ([]byte, error) {
n := s2.MaxEncodedLen(len(data))
b := make([]byte, n)
b = s2.Encode(b, data)
return b, nil
}
func (c *DefaultCompressor) s2Decompress(data []byte) ([]byte, error) {
_, err := s2.DecodedLen(data)
if err != nil {
return data, err
}
var buf bytes.Buffer
return s2.Decode(buf.Bytes(), data)
}
//
// Compressor interface
//
func (c *DefaultCompressor) Compress(data []byte) ([]byte, error) {
switch c.algorithm {
case s2Compression:
return c.s2Compress(data)
case gzipCompression:
return c.gzipCompress(data)
default:
return data, fmt.Errorf("unknown compression algorithm: %x", c.algorithm)
}
}
func (c *DefaultCompressor) Decompress(data []byte) ([]byte, error) {
switch c.algorithm {
case s2Compression:
return c.s2Decompress(data)
case gzipCompression:
return c.gzipDecompress(data)
default:
return data, fmt.Errorf("unknown compression algorithm: %x", c.algorithm)
}
}
func NewGzipCompressor() Compressor {
return &DefaultCompressor{
algorithm: gzipCompression,
}
}
func NewS2Compressor() Compressor {
return &DefaultCompressor{
algorithm: s2Compression,
}
}