forked from segmentio/kafka-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snappy.go
110 lines (93 loc) · 2.17 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package snappy
import (
"io"
"sync"
"github.com/klauspost/compress/s2"
"github.com/klauspost/compress/snappy"
)
// Framing is an enumeration type used to enable or disable xerial framing of
// snappy messages.
type Framing int
const (
Framed Framing = iota
Unframed
)
// Compression level.
type Compression int
const (
DefaultCompression Compression = iota
FasterCompression
BetterCompression
BestCompression
)
var (
readerPool sync.Pool
writerPool sync.Pool
)
// Codec is the implementation of a compress.Codec which supports creating
// readers and writers for kafka messages compressed with snappy.
type Codec struct {
// An optional framing to apply to snappy compression.
//
// Default to Framed.
Framing Framing
// Compression level.
Compression Compression
}
// Code implements the compress.Codec interface.
func (c *Codec) Code() int8 { return 2 }
// Name implements the compress.Codec interface.
func (c *Codec) Name() string { return "snappy" }
// NewReader implements the compress.Codec interface.
func (c *Codec) NewReader(r io.Reader) io.ReadCloser {
x, _ := readerPool.Get().(*xerialReader)
if x != nil {
x.Reset(r)
} else {
x = &xerialReader{
reader: r,
decode: snappy.Decode,
}
}
return &reader{xerialReader: x}
}
// NewWriter implements the compress.Codec interface.
func (c *Codec) NewWriter(w io.Writer) io.WriteCloser {
x, _ := writerPool.Get().(*xerialWriter)
if x != nil {
x.Reset(w)
} else {
x = &xerialWriter{writer: w}
}
x.framed = c.Framing == Framed
switch c.Compression {
case FasterCompression:
x.encode = s2.EncodeSnappy
case BetterCompression:
x.encode = s2.EncodeSnappyBetter
case BestCompression:
x.encode = s2.EncodeSnappyBest
default:
x.encode = snappy.Encode // aka. s2.EncodeSnappyBetter
}
return &writer{xerialWriter: 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
}