Debian Codegraph @

internal/s2/s2.go

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