-
Notifications
You must be signed in to change notification settings - Fork 8
/
mem.go
58 lines (52 loc) · 920 Bytes
/
mem.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
package mem
import (
"math/bits"
"sync"
)
var (
buf = newCirc[*sync.Pool](def)
shift = 10
mtx sync.RWMutex
)
const (
def = 10
)
func init() {
// push out 5 nil sync.Pool's
for idx := 0; idx < def; idx++ {
var pool sync.Pool
buf.append(&pool)
}
}
func Get(capacity int) []byte {
mtx.RLock()
defer mtx.RUnlock()
pos := bits.Len(uint(capacity)>>shift) - 1
if uint(pos) < def {
slice, ok := buf.at(pos).Get().(*[]byte)
if ok && cap(*slice) >= capacity {
return (*slice)[:capacity]
}
}
return make([]byte, capacity)
}
func Put(slice []byte) {
mtx.Lock()
defer mtx.Unlock()
// this -1 excludes 0's from the list.
pos := bits.Len(uint(cap(slice))>>shift) - 1
if pos < 0 && shift > 0 {
var pool sync.Pool
shift--
pos++
buf.prepend(&pool)
} else if pos >= def {
var pool sync.Pool
shift++
pos--
buf.append(&pool)
}
if uint(pos) < def {
buf.at(pos).Put(&slice)
}
}