Encode returns the encoded form of src for the given compression type. It also returns the indicator if the compression was performed. Encode may skip compressing for None type, but also when src is too large e.g. for Snappy block format. The buf is used as a buffer for returned encoding, and it mu
(t Type, src, buf []byte)
| 62 | // The buf is used as a buffer for returned encoding, and it must not overlap with |
| 63 | // src. It is valid to pass a nil buf. |
| 64 | func (e *Encoder) Encode(t Type, src, buf []byte) (_ []byte, compressed bool, err error) { |
| 65 | switch { |
| 66 | case len(src) == 0, t == "", t == None: |
| 67 | return src, false, nil |
| 68 | case t == Snappy: |
| 69 | // If MaxEncodedLen is less than 0 the record is too large to be compressed. |
| 70 | if snappy.MaxEncodedLen(len(src)) < 0 { |
| 71 | return src, false, nil |
| 72 | } |
| 73 | |
| 74 | // The snappy library uses `len` to calculate if we need a new buffer. |
| 75 | // In order to allocate as few buffers as possible make the length |
| 76 | // equal to the capacity. |
| 77 | buf = buf[:cap(buf)] |
| 78 | return snappy.Encode(buf, src), true, nil |
| 79 | case t == Zstd: |
| 80 | if e == nil { |
| 81 | return nil, false, errors.New("zstd requested but encoder was not initialized with NewEncoder()") |
| 82 | } |
| 83 | return e.w.EncodeAll(src, buf[:0]), true, nil |
| 84 | default: |
| 85 | return nil, false, fmt.Errorf("unsupported compression type: %s", t) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | // Decoder provides decompression functionality for supported compression types. |
| 90 | // It is agnostic to the content being decompressed, operating on byte slices of |