forked from francoispqt/gojay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode_stream_pool.go
59 lines (53 loc) · 1.48 KB
/
decode_stream_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
package gojay
import (
"io"
"sync"
)
var streamDecPool = sync.Pool{
New: newStreamDecoderPool,
}
// NewDecoder returns a new StreamDecoder.
// It takes an io.Reader implementation as data input.
// It initiates the done channel returned by Done().
func (s stream) NewDecoder(r io.Reader) *StreamDecoder {
dec := NewDecoder(r)
streamDec := &StreamDecoder{
Decoder: dec,
done: make(chan struct{}, 1),
mux: sync.RWMutex{},
}
return streamDec
}
func newStreamDecoderPool() interface{} {
return Stream.NewDecoder(nil)
}
// BorrowDecoder borrows a StreamDecoder from the pool.
// It takes an io.Reader implementation as data input.
// It initiates the done channel returned by Done().
//
// If no StreamEncoder is available in the pool, it returns a fresh one
func (s stream) BorrowDecoder(r io.Reader) *StreamDecoder {
return s.borrowDecoder(r, 512)
}
func (s stream) borrowDecoder(r io.Reader, bufSize int) *StreamDecoder {
streamDec := streamDecPool.Get().(*StreamDecoder)
streamDec.called = 0
streamDec.keysDone = 0
streamDec.cursor = 0
streamDec.err = nil
streamDec.r = r
streamDec.length = 0
streamDec.isPooled = 0
streamDec.done = make(chan struct{}, 1)
if bufSize > 0 {
streamDec.data = make([]byte, bufSize)
}
return streamDec
}
// 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 *StreamDecoder) Release() {
dec.isPooled = 1
streamDecPool.Put(dec)
}