forked from segmentio/kafka-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lz4.go
74 lines (62 loc) · 1.34 KB
/
lz4.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
package lz4
import (
"bytes"
"io/ioutil"
"github.com/pierrec/lz4"
kafka "github.com/segmentio/kafka-go"
)
func init() {
codec := NewCompressionCodec()
kafka.RegisterCompressionCodec(codec.Code(), func() kafka.CompressionCodec {
return codec
})
}
type CompressionCodec struct{}
func NewCompressionCodec() CompressionCodec {
return CompressionCodec{}
}
// Code implements the kafka.CompressionCodec interface.
func (c CompressionCodec) Code() int8 {
return 3
}
// Encode implements the kafka.CompressionCodec interface.
func (c CompressionCodec) Encode(dst, src []byte) (int, error) {
var buf bytes.Buffer
writer := lz4.NewWriter(&buf)
_, err := writer.Write(src)
if err != nil {
return 0, err
}
err = writer.Close()
if err != nil {
return 0, err
}
n, err := buf.WriteTo(&buffer{
data: dst,
})
return int(n), err
}
// Decode implements the kafka.CompressionCodec interface.
func (c CompressionCodec) Decode(dst, src []byte) (int, error) {
reader := lz4.NewReader(bytes.NewReader(src))
data, err := ioutil.ReadAll(reader)
if err != nil {
return 0, err
}
buf := buffer{
data: dst,
}
return buf.Write(data)
}
type buffer struct {
data []byte
size int
}
func (buf *buffer) Write(b []byte) (int, error) {
n := copy(buf.data[buf.size:], b)
buf.size += n
if n != len(b) {
return n, bytes.ErrTooLarge
}
return n, nil
}