forked from cortexproject/cortex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnappy.go
83 lines (69 loc) · 1.41 KB
/
snappy.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
package snappy
import (
"io"
"sync"
"github.com/golang/snappy"
"google.golang.org/grpc/encoding"
)
// Name is the name registered for the snappy compressor.
const Name = "snappy"
func init() {
encoding.RegisterCompressor(newCompressor())
}
type compressor struct {
writersPool sync.Pool
readersPool sync.Pool
}
func newCompressor() *compressor {
c := &compressor{}
c.readersPool = sync.Pool{
New: func() interface{} {
return snappy.NewReader(nil)
},
}
c.writersPool = sync.Pool{
New: func() interface{} {
return snappy.NewBufferedWriter(nil)
},
}
return c
}
func (c *compressor) Name() string {
return Name
}
func (c *compressor) Compress(w io.Writer) (io.WriteCloser, error) {
wr := c.writersPool.Get().(*snappy.Writer)
wr.Reset(w)
return writeCloser{wr, &c.writersPool}, nil
}
func (c *compressor) Decompress(r io.Reader) (io.Reader, error) {
dr := c.readersPool.Get().(*snappy.Reader)
dr.Reset(r)
return reader{dr, &c.readersPool}, nil
}
type writeCloser struct {
*snappy.Writer
pool *sync.Pool
}
func (w writeCloser) Close() error {
defer func() {
w.Writer.Reset(nil)
w.pool.Put(w.Writer)
}()
if w.Writer != nil {
return w.Writer.Close()
}
return nil
}
type reader struct {
reader *snappy.Reader
pool *sync.Pool
}
func (r reader) Read(p []byte) (n int, err error) {
n, err = r.reader.Read(p)
if err == io.EOF {
r.reader.Reset(nil)
r.pool.Put(r.reader)
}
return n, err
}