-
Notifications
You must be signed in to change notification settings - Fork 6
/
read_item.go
65 lines (56 loc) · 1.06 KB
/
read_item.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
package secureio
import (
"sync"
)
type readItem struct {
Data []byte
isBusy bool
isOneTimeUse bool
pool *readItemPool
}
type readItemPool struct {
storage sync.Pool
}
func newReadItemPool() *readItemPool {
pool := &readItemPool{}
pool.storage = sync.Pool{
New: func() interface{} {
return &readItem{
pool: pool,
}
},
}
return pool
}
func (pool *readItemPool) AcquireReadItem(maxSize uint32, isOneTimeUse bool) *readItem {
var item *readItem
if isOneTimeUse {
item = &readItem{
pool: pool,
}
} else {
item = pool.storage.Get().(*readItem)
}
if item.isBusy {
panic(`should not happened`)
}
item.isBusy = true
if cap(item.Data) < int(maxSize) {
item.Data = make([]byte, 0, maxSize)
}
return item
}
func (pool *readItemPool) Put(freeReadItem *readItem) {
if !freeReadItem.isBusy {
panic(`should not happened`)
}
if freeReadItem.isOneTimeUse {
return
}
freeReadItem.isBusy = false
freeReadItem.Data = freeReadItem.Data[:0]
pool.storage.Put(freeReadItem)
}
func (it *readItem) Release() {
it.pool.Put(it)
}