blob: af45fdaf94e2fd75cc56fd9991ca56f5a0a8c447 [file] [log] [blame]
William Kurkianea869482019-04-09 15:16:11 -04001package sarama
2
3import (
4 "bytes"
5 "compress/gzip"
6 "fmt"
7 "io/ioutil"
8 "sync"
9
khenaidoo106c61a2021-08-11 18:05:46 -040010 snappy "github.com/eapache/go-xerial-snappy"
William Kurkianea869482019-04-09 15:16:11 -040011 "github.com/pierrec/lz4"
12)
13
14var (
15 lz4ReaderPool = sync.Pool{
16 New: func() interface{} {
17 return lz4.NewReader(nil)
18 },
19 }
20
21 gzipReaderPool sync.Pool
22)
23
24func decompress(cc CompressionCodec, data []byte) ([]byte, error) {
25 switch cc {
26 case CompressionNone:
27 return data, nil
28 case CompressionGZIP:
khenaidoo106c61a2021-08-11 18:05:46 -040029 var err error
30 reader, ok := gzipReaderPool.Get().(*gzip.Reader)
31 if !ok {
William Kurkianea869482019-04-09 15:16:11 -040032 reader, err = gzip.NewReader(bytes.NewReader(data))
khenaidoo106c61a2021-08-11 18:05:46 -040033 } else {
34 err = reader.Reset(bytes.NewReader(data))
35 }
36
37 if err != nil {
38 return nil, err
William Kurkianea869482019-04-09 15:16:11 -040039 }
40
41 defer gzipReaderPool.Put(reader)
42
William Kurkianea869482019-04-09 15:16:11 -040043 return ioutil.ReadAll(reader)
44 case CompressionSnappy:
45 return snappy.Decode(data)
46 case CompressionLZ4:
khenaidoo106c61a2021-08-11 18:05:46 -040047 reader, ok := lz4ReaderPool.Get().(*lz4.Reader)
48 if !ok {
49 reader = lz4.NewReader(bytes.NewReader(data))
50 } else {
51 reader.Reset(bytes.NewReader(data))
52 }
William Kurkianea869482019-04-09 15:16:11 -040053 defer lz4ReaderPool.Put(reader)
54
William Kurkianea869482019-04-09 15:16:11 -040055 return ioutil.ReadAll(reader)
56 case CompressionZSTD:
57 return zstdDecompress(nil, data)
58 default:
59 return nil, PacketDecodingError{fmt.Sprintf("invalid compression specified (%d)", cc)}
60 }
61}