Debian Codegraph @

internal/klauspost_snappy/klauspost_snappy.go

raw
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 experimental/klauspost_snappy is a wrapper for using
20 // github.com/klauspost/compress/s2 in snappy compatibility mode with gRPC.
21 // It might be more efficient than the top-level snappy package which makes
22 // use of github.com/golang/snappy.
23 //
24 // Note that this is registered under the same "snappy" name with gRPC, so
25 // only one of the two packages should be used at a time.
26 package klauspost_snappy
27
28 // This code is based upon the gzip wrapper in github.com/grpc/grpc-go:
29 // https://github.com/grpc/grpc-go/blob/master/encoding/gzip/gzip.go
30
31 import (
32 "io"
33 "io/ioutil"
34 "sync"
35
36 snappylib "github.com/klauspost/compress/s2"
37 "google.golang.org/grpc/encoding"
38 )
39
40 const Name = "snappy"
41
42 type compressor struct {
43 poolCompressor sync.Pool
44 poolDecompressor sync.Pool
45 }
46
47 type writer struct {
48 *snappylib.Writer
49 pool *sync.Pool
50 }
51
52 type reader struct {
53 *snappylib.Reader
54 pool *sync.Pool
55 }
56
57 func PretendInit(clobbering bool) {
58 if !clobbering && encoding.GetCompressor(Name) != nil {
59 return
60 }
61
62 c := &compressor{}
63 c.poolCompressor.New = func() interface{} {
64 w := snappylib.NewWriter(ioutil.Discard, snappylib.WriterSnappyCompat())
65 return &writer{Writer: w, pool: &c.poolCompressor}
66 }
67 encoding.RegisterCompressor(c)
68 }
69
70 func (c *compressor) Compress(w io.Writer) (io.WriteCloser, error) {
71 z := c.poolCompressor.Get().(*writer)
72 z.Writer.Reset(w)
73 return z, nil
74 }
75
76 func (c *compressor) Decompress(r io.Reader) (io.Reader, error) {
77 z, inPool := c.poolDecompressor.Get().(*reader)
78 if !inPool {
79 newR := snappylib.NewReader(r, snappylib.ReaderAllocBlock(64<<10))
80 return &reader{Reader: newR, pool: &c.poolDecompressor}, nil
81 }
82 z.Reset(r)
83 return z, nil
84 }
85
86 func (c *compressor) Name() string {
87 return Name
88 }
89
90 func (z *writer) Close() error {
91 err := z.Writer.Close()
92 z.pool.Put(z)
93 return err
94 }
95
96 func (z *reader) Read(p []byte) (n int, err error) {
97 n, err = z.Reader.Read(p)
98 if err == io.EOF {
99 z.pool.Put(z)
100 }
101 return n, err
102 }