forked from opensearch-project/opensearch-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip.go
61 lines (51 loc) · 1.35 KB
/
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
// SPDX-License-Identifier: Apache-2.0
//
// The OpenSearch Contributors require contributions made to
// this file be licensed under the Apache-2.0 license or a
// compatible open source license.
package opensearchtransport
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"sync"
)
type gzipCompressor struct {
gzipWriterPool *sync.Pool
bufferPool *sync.Pool
}
// newGzipCompressor returns a new gzipCompressor that uses a sync.Pool to reuse gzip.Writers.
func newGzipCompressor() *gzipCompressor {
gzipWriterPool := sync.Pool{
New: func() any {
return gzip.NewWriter(io.Discard)
},
}
bufferPool := sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
return &gzipCompressor{
gzipWriterPool: &gzipWriterPool,
bufferPool: &bufferPool,
}
}
func (pg *gzipCompressor) compress(rc io.ReadCloser) (*bytes.Buffer, error) {
writer := pg.gzipWriterPool.Get().(*gzip.Writer)
defer pg.gzipWriterPool.Put(writer)
buf := pg.bufferPool.Get().(*bytes.Buffer)
buf.Reset()
writer.Reset(buf)
if _, err := io.Copy(writer, rc); err != nil {
return nil, fmt.Errorf("failed to compress request body: %w", err)
}
if err := writer.Close(); err != nil {
return nil, fmt.Errorf("failed to compress request body (during close): %w", err)
}
return buf, nil
}
func (pg *gzipCompressor) collectBuffer(buf *bytes.Buffer) {
pg.bufferPool.Put(buf)
}