Skip to content

Commit

Permalink
Re-use gzip.Writer
Browse files Browse the repository at this point in the history
  • Loading branch information
Pryz committed Jul 10, 2018
1 parent a21c848 commit a6306e2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
19 changes: 11 additions & 8 deletions gzip/gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func init() {

type CompressionCodec struct {
CompressionLevel int
writer *gzip.Writer
}

func NewCompressionCodec() CompressionCodec {
Expand All @@ -25,6 +26,7 @@ func NewCompressionCodec() CompressionCodec {
func NewCompressionCodecWith(level int) CompressionCodec {
return CompressionCodec{
CompressionLevel: level,
writer: gzip.NewWriter(nil),
}
}

Expand All @@ -35,21 +37,22 @@ func (c CompressionCodec) Code() int8 {

// Encode implements the kafka.CompressionCodec interface.
func (c CompressionCodec) Encode(dst, src []byte) (int, error) {
var buf bytes.Buffer
writer := gzip.NewWriter(&buf)
_, err := writer.Write(src)
buf := buffer{
data: dst,
}
c.writer.Reset(&buf)

_, err := c.writer.Write(src)
if err != nil {
return 0, err
}
err = writer.Close()

err = c.writer.Close()
if err != nil {
return 0, err
}

n, err := buf.WriteTo(&buffer{
data: dst,
})
return int(n), err
return buf.size, err
}

// Decode implements the kafka.CompressionCodec interface.
Expand Down
2 changes: 1 addition & 1 deletion gzip/gzip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ func TestGzip(t *testing.T) {
r1 := make([]byte, 6*len(payload))
r2 := make([]byte, len(payload))

c := CompressionCodec{}
c := NewCompressionCodec()

t.Run("encode", func(t *testing.T) {
n, err := c.Encode(r1, payload)
Expand Down

0 comments on commit a6306e2

Please sign in to comment.