blob: af45fdaf94e2fd75cc56fd9991ca56f5a0a8c447 [file] [log] [blame]
Scott Bakered4efab2020-01-13 19:12:25 -08001package sarama
2
3import (
4 "bytes"
5 "compress/gzip"
6 "fmt"
7 "io/ioutil"
8 "sync"
9
David K. Bainbridgebd6b2882021-08-26 13:31:02 +000010 snappy "github.com/eapache/go-xerial-snappy"
Scott Bakered4efab2020-01-13 19:12:25 -080011 "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:
David K. Bainbridgebd6b2882021-08-26 13:31:02 +000029 var err error
30 reader, ok := gzipReaderPool.Get().(*gzip.Reader)
31 if !ok {
Scott Bakered4efab2020-01-13 19:12:25 -080032 reader, err = gzip.NewReader(bytes.NewReader(data))
David K. Bainbridgebd6b2882021-08-26 13:31:02 +000033 } else {
34 err = reader.Reset(bytes.NewReader(data))
35 }
36
37 if err != nil {
38 return nil, err
Scott Bakered4efab2020-01-13 19:12:25 -080039 }
40
41 defer gzipReaderPool.Put(reader)
42
Scott Bakered4efab2020-01-13 19:12:25 -080043 return ioutil.ReadAll(reader)
44 case CompressionSnappy:
45 return snappy.Decode(data)
46 case CompressionLZ4:
David K. Bainbridgebd6b2882021-08-26 13:31:02 +000047 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 }
Scott Bakered4efab2020-01-13 19:12:25 -080053 defer lz4ReaderPool.Put(reader)
54
Scott Bakered4efab2020-01-13 19:12:25 -080055 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}