forked from francoispqt/gojay
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdecode_pool.go
116 lines (97 loc) · 1.92 KB
/
decode_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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package gojay
import (
"io"
"sync"
)
var decPool = sync.Pool{
New: newDecoderPool,
}
func init() {
for i := 0; i < 32; i++ {
decPool.Put(NewDecoder(nil))
}
}
// NewDecoder returns a new decoder.
// It takes an io.Reader implementation as data input.
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{
called: 0,
cursor: 0,
keysDone: 0,
err: nil,
r: r,
data: make([]byte, 512),
length: 0,
isPooled: 0,
}
}
func newDecoderPool() interface{} {
return NewDecoder(nil)
}
// BorrowDecoder borrows a Decoder from the pool.
// It takes an io.Reader implementation as data input.
//
// In order to benefit from the pool, a borrowed decoder must be released after usage.
func BorrowDecoder(r io.Reader) *Decoder {
return borrowDecoder(r, 512)
}
func borrowDecoder(r io.Reader, bufSize int) *Decoder {
dec := decPool.Get().(*Decoder)
dec.called = 0
dec.keysDone = 0
dec.cursor = 0
dec.err = nil
dec.r = r
dec.length = 0
dec.isPooled = 0
if bufSize > 0 {
dec.data = make([]byte, bufSize)
}
return dec
}
// Release sends back a Decoder to the pool.
// If a decoder is used after calling Release
// a panic will be raised with an InvalidUsagePooledDecoderError error.
func (dec *Decoder) Release() {
dec.isPooled = 1
decPool.Put(dec)
}
// ByteBuffer
const (
defCap = 1024
)
type ByteBuffer struct {
B []byte
isReleased bool
}
func (b *ByteBuffer) Release() {
putBytes(b)
}
func (b *ByteBuffer) Set(p []byte) {
b.B = append(b.B[:0], p...)
}
func (b *ByteBuffer) Len() int {
return len(b.B)
}
//Release s.e.
var bytesPool = sync.Pool{
New: func() interface{} {
return &ByteBuffer{B: make([]byte, defCap)}
},
}
func getBytes(l int) (b *ByteBuffer) {
b = bytesPool.Get().(*ByteBuffer)
if cap(b.B) < l {
b.B = make([]byte, l)
} else {
b.B = b.B[:l]
}
b.isReleased = false
return b
}
func putBytes(b *ByteBuffer) {
if !b.isReleased {
b.isReleased = true
bytesPool.Put(b)
}
}