Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [diff] [blame] | 1 | package sarama |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "compress/gzip" |
| 6 | "fmt" |
| 7 | "io/ioutil" |
| 8 | "sync" |
| 9 | |
khenaidoo | 7d3c558 | 2021-08-11 18:09:44 -0400 | [diff] [blame] | 10 | snappy "github.com/eapache/go-xerial-snappy" |
Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [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 | 7d3c558 | 2021-08-11 18:09:44 -0400 | [diff] [blame] | 29 | var err error |
| 30 | reader, ok := gzipReaderPool.Get().(*gzip.Reader) |
| 31 | if !ok { |
Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [diff] [blame] | 32 | reader, err = gzip.NewReader(bytes.NewReader(data)) |
khenaidoo | 7d3c558 | 2021-08-11 18:09:44 -0400 | [diff] [blame] | 33 | } else { |
| 34 | err = reader.Reset(bytes.NewReader(data)) |
| 35 | } |
| 36 | |
| 37 | if err != nil { |
| 38 | return nil, err |
Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | defer gzipReaderPool.Put(reader) |
| 42 | |
Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [diff] [blame] | 43 | return ioutil.ReadAll(reader) |
| 44 | case CompressionSnappy: |
| 45 | return snappy.Decode(data) |
| 46 | case CompressionLZ4: |
khenaidoo | 7d3c558 | 2021-08-11 18:09:44 -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 | } |
Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [diff] [blame] | 53 | defer lz4ReaderPool.Put(reader) |
| 54 | |
Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [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 | } |