-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallocator.go
79 lines (66 loc) · 1.44 KB
/
allocator.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
/*
Shared memory allocator. Currently we're just allocating memory on a fixed
"heap", no free.
*/
package main
import (
"github.com/apache/arrow/go/arrow/memory"
)
const (
memAlign = 64
)
var (
// Make sure ShmAllocator implements memory.Allocator
_ memory.Allocator = &ShmAllocator{}
)
// ShmAllocator is a shared memory allocator
type ShmAllocator struct {
shm *SharedMemory
offset int
}
// NewShmAlloactor returns a new shared memory allocator
func NewShmAlloactor(id string, maxSize int) (*ShmAllocator, error) {
size := align(maxSize, memAlign)
shm, err := NewSharedMemory(id, size)
if err != nil {
return nil, err
}
return &ShmAllocator{shm: shm}, nil
}
// Allocate memory
func (a *ShmAllocator) Allocate(size int) []byte {
size = align(size, memAlign)
data := a.shm.Data()
offset := a.offset
if offset+size > cap(data) {
panic("out of memory")
}
a.offset += size
return data[offset : offset+size]
}
// Reallocate reallocates memory
func (a *ShmAllocator) Reallocate(size int, b []byte) []byte {
if size == len(b) {
return b
}
data := a.Allocate(size)
copy(data, b)
return data
}
// Free frees the memory
func (a *ShmAllocator) Free(b []byte) {
// TODO: Keep free list?
}
// Close closes the shared memory
func (a *ShmAllocator) Close(del bool) error {
if a.shm == nil {
return nil
}
err := a.shm.Close(del)
a.shm = nil
return err
}
func align(num, size int) int {
n := (num + size - 1) / size
return n * size
}