-
Notifications
You must be signed in to change notification settings - Fork 104
/
compressor.go
43 lines (34 loc) · 972 Bytes
/
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
package gocb
import "github.com/golang/snappy"
type compressor struct {
CompressionEnabled bool
CompressionMinSize uint32
CompressionMinRatio float64
}
type possiblyCompressedResponse interface {
GetContentUncompressed() []byte
GetContentCompressed() []byte
}
func (c *compressor) Compress(val []byte) ([]byte, bool) {
if !c.CompressionEnabled {
return val, false
}
valueLen := len(val)
if valueLen > int(c.CompressionMinSize) {
compressedValue := snappy.Encode(nil, val)
if float64(len(compressedValue))/float64(valueLen) <= c.CompressionMinRatio {
return compressedValue, true
}
}
return val, false
}
func (c *compressor) Decompress(val possiblyCompressedResponse) ([]byte, error) {
if val.GetContentUncompressed() != nil {
return val.GetContentUncompressed(), nil
}
newValue, err := snappy.Decode(nil, val.GetContentCompressed())
if err != nil {
return nil, wrapError(err, "failed to decode content")
}
return newValue, nil
}