blob: af45fdaf94e2fd75cc56fd9991ca56f5a0a8c447 [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001package sarama
2
3import (
4 "bytes"
5 "compress/gzip"
6 "fmt"
7 "io/ioutil"
8 "sync"
9
khenaidoo7d3c5582021-08-11 18:09:44 -040010 snappy "github.com/eapache/go-xerial-snappy"
Holger Hildebrandtfa074992020-03-27 15:42:06 +000011 "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:
khenaidoo7d3c5582021-08-11 18:09:44 -040029 var err error
30 reader, ok := gzipReaderPool.Get().(*gzip.Reader)
31 if !ok {
Holger Hildebrandtfa074992020-03-27 15:42:06 +000032 reader, err = gzip.NewReader(bytes.NewReader(data))
khenaidoo7d3c5582021-08-11 18:09:44 -040033 } else {
34 err = reader.Reset(bytes.NewReader(data))
35 }
36
37 if err != nil {
38 return nil, err
Holger Hildebrandtfa074992020-03-27 15:42:06 +000039 }
40
41 defer gzipReaderPool.Put(reader)
42
Holger Hildebrandtfa074992020-03-27 15:42:06 +000043 return ioutil.ReadAll(reader)
44 case CompressionSnappy:
45 return snappy.Decode(data)
46 case CompressionLZ4:
khenaidoo7d3c5582021-08-11 18:09:44 -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 }
Holger Hildebrandtfa074992020-03-27 15:42:06 +000053 defer lz4ReaderPool.Put(reader)
54
Holger Hildebrandtfa074992020-03-27 15:42:06 +000055 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}