-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb_safe_mpool.go
80 lines (70 loc) · 1.42 KB
/
b_safe_mpool.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
// Copyright 2020 lesismal. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package mpool
import (
"sync"
)
type SafeMemPool struct {
bufSize int
freeSize int
pool *sync.Pool
}
func NewSafeMpool(bufSize, freeSize int) Allocator {
if bufSize <= 0 {
bufSize = 64
}
if freeSize <= 0 {
freeSize = 64 * 1024
}
if freeSize < bufSize {
freeSize = bufSize
}
mp := &SafeMemPool{
bufSize: bufSize,
freeSize: freeSize,
pool: &sync.Pool{},
}
mp.pool.New = func() interface{} {
buf := make([]byte, bufSize)
return &buf
}
return mp
}
func (mp *SafeMemPool) Malloc(size int) []byte {
if size > mp.freeSize {
return make([]byte, size)
}
pbuf := mp.pool.Get().(*[]byte)
n := cap(*pbuf)
if n < size {
*pbuf = append((*pbuf)[:n], make([]byte, size-n)...)
}
return (*pbuf)[:size]
}
func (mp *SafeMemPool) Realloc(buf []byte, size int) []byte {
if size <= cap(buf) {
return buf[:size]
}
if cap(buf) < mp.freeSize {
pbuf := mp.pool.Get().(*[]byte)
n := cap(buf)
if n < size {
*pbuf = append((*pbuf)[:n], make([]byte, size-n)...)
}
*pbuf = (*pbuf)[:size]
copy(*pbuf, buf)
mp.Free(buf)
return *pbuf
}
return append(buf[:cap(buf)], make([]byte, size-cap(buf))...)[:size]
}
func (mp *SafeMemPool) Free(buf []byte) {
if cap(buf) > mp.freeSize {
return
}
for i := range buf {
buf[i] = 0
}
mp.pool.Put(&buf)
}