-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
compressor.go
76 lines (60 loc) ยท 1.36 KB
/
compressor.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
package protocol
import (
"bytes"
"io"
"github.com/golang/snappy"
"github.com/smallnest/rpcx/util"
)
// Compressor defines a common compression interface.
type Compressor interface {
Zip([]byte) ([]byte, error)
Unzip([]byte) ([]byte, error)
}
// GzipCompressor implements gzip compressor.
type GzipCompressor struct {
}
func (c GzipCompressor) Zip(data []byte) ([]byte, error) {
return util.Zip(data)
}
func (c GzipCompressor) Unzip(data []byte) ([]byte, error) {
return util.Unzip(data)
}
type RawDataCompressor struct {
}
func (c RawDataCompressor) Zip(data []byte) ([]byte, error) {
return data, nil
}
func (c RawDataCompressor) Unzip(data []byte) ([]byte, error) {
return data, nil
}
// SnappyCompressor implements snappy compressor
type SnappyCompressor struct {
}
func (c *SnappyCompressor) Zip(data []byte) ([]byte, error) {
if len(data) == 0 {
return data, nil
}
var buffer bytes.Buffer
writer := snappy.NewBufferedWriter(&buffer)
_, err := writer.Write(data)
if err != nil {
writer.Close()
return nil, err
}
err = writer.Close()
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func (c *SnappyCompressor) Unzip(data []byte) ([]byte, error) {
if len(data) == 0 {
return data, nil
}
reader := snappy.NewReader(bytes.NewReader(data))
out, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
return out, err
}