| 1 |
/* |
| 2 |
* |
| 3 |
* Copyright 2017 gRPC authors. |
| 4 |
* |
| 5 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
* you may not use this file except in compliance with the License. |
| 7 |
* You may obtain a copy of the License at |
| 8 |
* |
| 9 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
* |
| 11 |
* Unless required by applicable law or agreed to in writing, software |
| 12 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
* See the License for the specific language governing permissions and |
| 15 |
* limitations under the License. |
| 16 |
* |
| 17 |
*/ |
| 18 |
|
| 19 |
// Package lz4 is a wrapper for using github.com/pierrec/lz4 with gRPC. |
| 20 |
package lz4 |
| 21 |
|
| 22 |
// This code is based upon the gzip wrapper in github.com/grpc/grpc-go: |
| 23 |
// https://github.com/grpc/grpc-go/blob/master/encoding/gzip/gzip.go |
| 24 |
|
| 25 |
import ( |
| 26 |
"io" |
| 27 |
"io/ioutil" |
| 28 |
"sync" |
| 29 |
|
| 30 |
lz4lib "github.com/pierrec/lz4/v4" |
| 31 |
"google.golang.org/grpc/encoding" |
| 32 |
) |
| 33 |
|
| 34 |
const Name = "lz4" |
| 35 |
|
| 36 |
type compressor struct { |
| 37 |
poolCompressor sync.Pool |
| 38 |
poolDecompressor sync.Pool |
| 39 |
} |
| 40 |
|
| 41 |
type writer struct { |
| 42 |
*lz4lib.Writer |
| 43 |
pool *sync.Pool |
| 44 |
} |
| 45 |
|
| 46 |
type reader struct { |
| 47 |
*lz4lib.Reader |
| 48 |
pool *sync.Pool |
| 49 |
} |
| 50 |
|
| 51 |
func PretendInit(clobbering bool) { |
| 52 |
if !clobbering && encoding.GetCompressor(Name) != nil { |
| 53 |
return |
| 54 |
} |
| 55 |
|
| 56 |
c := &compressor{} |
| 57 |
c.poolCompressor.New = func() interface{} { |
| 58 |
w := lz4lib.NewWriter(ioutil.Discard) |
| 59 |
return &writer{Writer: w, pool: &c.poolCompressor} |
| 60 |
} |
| 61 |
encoding.RegisterCompressor(c) |
| 62 |
} |
| 63 |
|
| 64 |
func (c *compressor) Compress(w io.Writer) (io.WriteCloser, error) { |
| 65 |
z := c.poolCompressor.Get().(*writer) |
| 66 |
z.Writer.Reset(w) |
| 67 |
return z, nil |
| 68 |
} |
| 69 |
|
| 70 |
func (c *compressor) Decompress(r io.Reader) (io.Reader, error) { |
| 71 |
z, inPool := c.poolDecompressor.Get().(*reader) |
| 72 |
if !inPool { |
| 73 |
newR := lz4lib.NewReader(r) |
| 74 |
return &reader{Reader: newR, pool: &c.poolDecompressor}, nil |
| 75 |
} |
| 76 |
z.Reset(r) |
| 77 |
return z, nil |
| 78 |
} |
| 79 |
|
| 80 |
func (c *compressor) Name() string { |
| 81 |
return Name |
| 82 |
} |
| 83 |
|
| 84 |
func (z *writer) Close() error { |
| 85 |
err := z.Writer.Close() |
| 86 |
z.pool.Put(z) |
| 87 |
return err |
| 88 |
} |
| 89 |
|
| 90 |
func (z *reader) Read(p []byte) (n int, err error) { |
| 91 |
n, err = z.Reader.Read(p) |
| 92 |
if err == io.EOF { |
| 93 |
z.pool.Put(z) |
| 94 |
} |
| 95 |
return n, err |
| 96 |
} |