forked from segmentio/kafka-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnappy.go
92 lines (73 loc) · 1.84 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
84
85
86
87
88
89
90
91
92
package snappy
import (
"io"
"sync"
"github.com/golang/snappy"
kafka "github.com/segmentio/kafka-go"
)
func init() {
kafka.RegisterCompressionCodec(NewCompressionCodec())
}
// Framing is an enumeration type used to enable or disable xerial framing of
// snappy messages.
type Framing int
const (
Framed Framing = iota
Unframed
)
const (
Code = 2
)
type CompressionCodec struct{ framing Framing }
func NewCompressionCodec() *CompressionCodec {
return NewCompressionCodecFraming(Framed)
}
func NewCompressionCodecFraming(framing Framing) *CompressionCodec {
return &CompressionCodec{framing}
}
// Code implements the kafka.CompressionCodec interface.
func (c *CompressionCodec) Code() int8 { return Code }
// Name implements the kafka.CompressionCodec interface.
func (c *CompressionCodec) Name() string { return "snappy" }
// NewReader implements the kafka.CompressionCodec interface.
func (c *CompressionCodec) NewReader(r io.Reader) io.ReadCloser {
x := readerPool.Get().(*xerialReader)
x.Reset(r)
return &reader{x}
}
// NewWriter implements the kafka.CompressionCodec interface.
func (c *CompressionCodec) NewWriter(w io.Writer) io.WriteCloser {
x := writerPool.Get().(*xerialWriter)
x.Reset(w)
x.framed = c.framing == Framed
return &writer{x}
}
type reader struct{ *xerialReader }
func (r *reader) Close() (err error) {
if x := r.xerialReader; x != nil {
r.xerialReader = nil
x.Reset(nil)
readerPool.Put(x)
}
return
}
type writer struct{ *xerialWriter }
func (w *writer) Close() (err error) {
if x := w.xerialWriter; x != nil {
w.xerialWriter = nil
err = x.Flush()
x.Reset(nil)
writerPool.Put(x)
}
return
}
var readerPool = sync.Pool{
New: func() interface{} {
return &xerialReader{decode: snappy.Decode}
},
}
var writerPool = sync.Pool{
New: func() interface{} {
return &xerialWriter{encode: snappy.Encode}
},
}