Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 1 | package sarama |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "compress/gzip" |
| 6 | "fmt" |
| 7 | "io/ioutil" |
| 8 | "sync" |
| 9 | |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 10 | snappy "github.com/eapache/go-xerial-snappy" |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 11 | "github.com/pierrec/lz4" |
| 12 | ) |
| 13 | |
| 14 | var ( |
| 15 | lz4ReaderPool = sync.Pool{ |
| 16 | New: func() interface{} { |
| 17 | return lz4.NewReader(nil) |
| 18 | }, |
| 19 | } |
| 20 | |
| 21 | gzipReaderPool sync.Pool |
| 22 | ) |
| 23 | |
| 24 | func decompress(cc CompressionCodec, data []byte) ([]byte, error) { |
| 25 | switch cc { |
| 26 | case CompressionNone: |
| 27 | return data, nil |
| 28 | case CompressionGZIP: |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 29 | var err error |
| 30 | reader, ok := gzipReaderPool.Get().(*gzip.Reader) |
| 31 | if !ok { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 32 | reader, err = gzip.NewReader(bytes.NewReader(data)) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 33 | } else { |
| 34 | err = reader.Reset(bytes.NewReader(data)) |
| 35 | } |
| 36 | |
| 37 | if err != nil { |
| 38 | return nil, err |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | defer gzipReaderPool.Put(reader) |
| 42 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 43 | return ioutil.ReadAll(reader) |
| 44 | case CompressionSnappy: |
| 45 | return snappy.Decode(data) |
| 46 | case CompressionLZ4: |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 47 | 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 Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 53 | defer lz4ReaderPool.Put(reader) |
| 54 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 55 | 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 | } |