-
Notifications
You must be signed in to change notification settings - Fork 2
/
gzip.go
67 lines (55 loc) · 1.26 KB
/
gzip.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
package compression
import (
"bytes"
"io"
"github.com/hstreamdb/hstreamdb-go/util"
"github.com/klauspost/compress/gzip"
"go.uber.org/zap"
)
type GzipCompressor struct {
encoder *gzip.Writer
}
func NewGzipCompressor() Compressor {
zw := gzip.NewWriter(nil)
return &GzipCompressor{
encoder: zw,
}
}
func (g *GzipCompressor) GetAlgorithm() CompressionType {
return Gzip
}
func (g *GzipCompressor) Compress(dst, src []byte) []byte {
buffer := bytes.NewBuffer(dst)
g.encoder.Reset(buffer)
if _, err := g.encoder.Write(src); err != nil {
util.Logger().Error("gzip compress error", zap.String("error", err.Error()))
return nil
}
g.encoder.Flush()
return buffer.Bytes()
}
func (g *GzipCompressor) Close() {
g.encoder.Close()
}
type GzipDeCompressor struct {
decoder *gzip.Reader
}
func NewGzipDeCompressor() Decompressor {
return &GzipDeCompressor{
decoder: new(gzip.Reader),
}
}
func (g *GzipDeCompressor) GetAlgorithm() CompressionType {
return Gzip
}
func (g *GzipDeCompressor) Decompress(dst, src []byte) ([]byte, error) {
if err := g.decoder.Reset(bytes.NewBuffer(src)); err != nil {
return nil, err
}
buffer := bytes.NewBuffer(dst)
io.Copy(buffer, g.decoder)
return buffer.Bytes(), nil
}
func (g *GzipDeCompressor) Close() {
g.decoder.Close()
}