-
Notifications
You must be signed in to change notification settings - Fork 93
/
compress_gzip.go
86 lines (77 loc) · 1.62 KB
/
compress_gzip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
package codec
import (
"bytes"
"compress/gzip"
"io"
"sync"
)
func init() {
RegisterCompressor(CompressTypeGzip, &GzipCompress{})
}
// GzipCompress is gzip compressor.
type GzipCompress struct {
readerPool sync.Pool
writerPool sync.Pool
}
// Compress returns binary data compressed by gzip.
func (c *GzipCompress) Compress(in []byte) ([]byte, error) {
if len(in) == 0 {
return in, nil
}
buffer := &bytes.Buffer{}
z, ok := c.writerPool.Get().(*gzip.Writer)
if !ok {
z = gzip.NewWriter(buffer)
} else {
z.Reset(buffer)
}
defer c.writerPool.Put(z)
if _, err := z.Write(in); err != nil {
return nil, err
}
if err := z.Close(); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
// Decompress returns binary data decompressed by gzip.
func (c *GzipCompress) Decompress(in []byte) ([]byte, error) {
if len(in) == 0 {
return in, nil
}
br := bytes.NewReader(in)
z, ok := c.readerPool.Get().(*gzip.Reader)
defer func() {
if z != nil {
c.readerPool.Put(z)
}
}()
if !ok {
gr, err := gzip.NewReader(br)
if err != nil {
return nil, err
}
z = gr
} else {
if err := z.Reset(br); err != nil {
return nil, err
}
}
out, err := io.ReadAll(z)
if err != nil {
return nil, err
}
return out, nil
}