compress returns the input bytes compressed by compressor or cp. If both compressors are nil, or if the message has zero length, returns nil, indicating no compression was done. TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, pool mem.BufferPool)
| 832 | // |
| 833 | // TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor. |
| 834 | func compress(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, pool mem.BufferPool) (mem.BufferSlice, payloadFormat, error) { |
| 835 | if (compressor == nil && cp == nil) || in.Len() == 0 { |
| 836 | return nil, compressionNone, nil |
| 837 | } |
| 838 | var out mem.BufferSlice |
| 839 | w := mem.NewWriter(&out, pool) |
| 840 | wrapErr := func(err error) error { |
| 841 | out.Free() |
| 842 | return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) |
| 843 | } |
| 844 | if compressor != nil { |
| 845 | z, err := compressor.Compress(w) |
| 846 | if err != nil { |
| 847 | return nil, compressionNone, wrapErr(err) |
| 848 | } |
| 849 | for _, b := range in { |
| 850 | if _, err := z.Write(b.ReadOnlyData()); err != nil { |
| 851 | return nil, compressionNone, wrapErr(err) |
| 852 | } |
| 853 | } |
| 854 | if err := z.Close(); err != nil { |
| 855 | return nil, compressionNone, wrapErr(err) |
| 856 | } |
| 857 | } else { |
| 858 | // This is obviously really inefficient since it fully materializes the data, but |
| 859 | // there is no way around this with the old Compressor API. At least it attempts |
| 860 | // to return the buffer to the provider, in the hopes it can be reused (maybe |
| 861 | // even by a subsequent call to this very function). |
| 862 | buf := in.MaterializeToBuffer(pool) |
| 863 | defer buf.Free() |
| 864 | if err := cp.Do(w, buf.ReadOnlyData()); err != nil { |
| 865 | return nil, compressionNone, wrapErr(err) |
| 866 | } |
| 867 | } |
| 868 | return out, compressionMade, nil |
| 869 | } |
| 870 | |
| 871 | const ( |
| 872 | payloadLen = 1 |