-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
writer_pool.go
63 lines (51 loc) · 1.09 KB
/
writer_pool.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package translator // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/awsxrayexporter/internal/translator"
import (
"bytes"
"encoding/json"
"sync"
)
const (
maxBufSize = 65536
)
type writer struct {
buffer *bytes.Buffer
encoder *json.Encoder
}
type writerPool struct {
pool *sync.Pool
}
func newWriterPool(size int) *writerPool {
pool := &sync.Pool{
New: func() any {
var (
buffer = bytes.NewBuffer(make([]byte, 0, size))
encoder = json.NewEncoder(buffer)
)
return &writer{
buffer: buffer,
encoder: encoder,
}
},
}
return &writerPool{pool: pool}
}
func (w *writer) Reset() {
w.buffer.Reset()
}
func (w *writer) Encode(v any) error {
return w.encoder.Encode(v)
}
func (w *writer) String() string {
return w.buffer.String()
}
func (writerPool *writerPool) borrow() *writer {
return writerPool.pool.Get().(*writer)
}
func (writerPool *writerPool) release(w *writer) {
if w.buffer.Cap() < maxBufSize {
w.buffer.Reset()
writerPool.pool.Put(w)
}
}