-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
module_heap.go
98 lines (77 loc) · 2.28 KB
/
module_heap.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package core
import (
"errors"
"fmt"
"unsafe"
)
var (
ErrZeroOrNegAlignment = errors.New("zero or negative alignment")
ErrZeroOrNegAllocationSize = errors.New("zero or negative allocation size")
ErrInvalidInitialHeapCapacity = errors.New("invalid initial heap capacity")
)
type ModuleHeap struct {
Alloc func(size int, alignment int) HeapAddress
DeallocAll func()
}
type HeapAddress *byte
func HeapAddressUintptr(addr HeapAddress) uintptr {
return uintptr(unsafe.Pointer(addr))
}
//go:nocheckptr
func HeapAddressFromUintptr(ptr uintptr) HeapAddress {
return (HeapAddress)(unsafe.Pointer(ptr))
}
// Alloc allocates $size bytes and returns the starting position of the allocated memory segment.
func Alloc[T any](h *ModuleHeap, size int, alignment int) HeapAddress {
return h.Alloc(size, alignment)
}
// DeallocAll de-allocates the heap content, the heap is no longer usable.
func DeallocAll(h *ModuleHeap) {
h.DeallocAll()
}
func NewArenaHeap(initialCapacity int) *ModuleHeap {
if initialCapacity < 100 {
panic(fmt.Errorf("%w: too small", ErrInvalidInitialHeapCapacity))
}
const (
DEFAULT_NEW_SEGMENT_SIZE = 1 << 16
)
//temporary naive implementation
segments := [][]byte{make([]byte, 0, initialCapacity)}
heap := &ModuleHeap{}
heap.Alloc = func(size int, alignment int) HeapAddress {
if alignment <= 0 {
panic(fmt.Errorf("%w: %d", ErrZeroOrNegAlignment, alignment))
}
if size <= 0 {
panic(fmt.Errorf("%w: %d", ErrZeroOrNegAllocationSize, alignment))
}
var chosenSegment []byte
var chosenSegmentIndex int //index in segments
for _, segment := range segments {
if cap(segment)-len(segment) >= size+alignment {
chosenSegment = segment
break
}
}
if chosenSegment == nil {
chosenSegment = make([]byte, 0, max(size+alignment-1, DEFAULT_NEW_SEGMENT_SIZE))
segments = append(segments, chosenSegment)
}
startIndex := (len(chosenSegment) + alignment - 1) / alignment * alignment
chosenSegment = chosenSegment[:startIndex+size]
segments[chosenSegmentIndex] = chosenSegment
ptr := &chosenSegment[startIndex]
return HeapAddress(ptr)
}
heap.DeallocAll = func() {
for _, segment := range segments {
clear(segment)
}
segments = nil
//TODO: recycle the arena
heap.Alloc = nil
heap.DeallocAll = nil
}
return heap
}