-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallocation.go
67 lines (57 loc) · 1.64 KB
/
allocation.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
package s2randomaccess
import (
"math"
"sync"
)
// Allocator defines the methods a custom allocator needs to have.
type Allocator interface {
Alloc(n int) []byte
Free([]byte)
}
type defaultAllocator struct{}
func (defaultAllocator) Alloc(n int) []byte {
return make([]byte, n)
}
func (defaultAllocator) Free(b []byte) {
}
// WithAllocator can be passed to New() to use an alternative allocator.
func WithAllocator(a Allocator) Option {
return func(s *Seeker) error {
s.allocator = a
return nil
}
}
const (
SyncPoolAllocatorSkipBuckets = 6
SyncPoolAllocatorLargestBucket = 33
)
// SyncPoolAllocator is an Allocator that uses one `sync.Pool` for each n**2 for n in (SyncPoolAllocatorSkipBuckets, SyncPoolAllocatorLargestBucket].
type SyncPoolAllocator struct {
Pools [SyncPoolAllocatorLargestBucket - SyncPoolAllocatorSkipBuckets]sync.Pool
}
func (a *SyncPoolAllocator) Alloc(n int) []byte {
class := int(math.Ceil(math.Log2(float64(n))))
if class < SyncPoolAllocatorSkipBuckets || class >= SyncPoolAllocatorLargestBucket {
// Too small/big for the predeclared classes.
return make([]byte, n)
}
for {
ret := a.Pools[class-SyncPoolAllocatorSkipBuckets].Get()
if ret == nil {
return make([]byte, n, 1<<class)
}
b := ret.([]byte)
if n <= cap(b) {
return b[:n]
}
// Someone put a too-small buffer into this bucket. Drop it.
}
}
func (a *SyncPoolAllocator) Free(b []byte) {
class := int(math.Floor(math.Log2(float64(cap(b)))))
if class < SyncPoolAllocatorSkipBuckets || class >= SyncPoolAllocatorLargestBucket {
// Too small/big for the predeclared classes.
return
}
a.Pools[class-SyncPoolAllocatorSkipBuckets].Put(b)
}