-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser_manager.go
50 lines (45 loc) · 1.4 KB
/
parser_manager.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
package fastparse
import (
"io"
"sync"
)
// ParserManager is used to manage the parsing of arguments.
type ParserManager struct {
initProperly bool
pool *sync.Pool
}
// Used to allocate a fresh scratchpad on the fly.
func freshScratchpadAlloc(MessageLen int) func() interface{} {
return func() interface{} {
return &scratchpad{
slice: make([]byte, MessageLen),
sliceLen: MessageLen,
}
}
}
// NewParserManager is used to create a new parser manager.
// MessageLen is the maximum length of each message, and PreAllocatedPads are the amount of scratchpads which will be pre-allocated.
// Each pre-allocated scratchpad uses the amount of bytes which a message would take, but they mean that the memory will not need to be allocated on the fly later.
func NewParserManager(MessageLen, PreAllocatedPads int) *ParserManager {
p := &ParserManager{
initProperly: true,
pool: &sync.Pool{New: freshScratchpadAlloc(MessageLen)},
}
for i := 0; i < PreAllocatedPads; i++ {
p.pool.Put(&scratchpad{
slice: make([]byte, MessageLen),
sliceLen: MessageLen,
pool: p.pool,
})
}
return p
}
// Parser is used to get a parser from the manager.
func (m *ParserManager) Parser(r io.ReadSeeker) *Parser {
if !m.initProperly {
panic("The ParserManager needs to be created with NewParserManager")
}
pad := m.pool.Get().(*scratchpad)
pad.reset()
return &Parser{initProperly: true, pad: pad, r: r}
}