forked from joetifa2003/mm-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmm.go
50 lines (42 loc) · 1.27 KB
/
mm.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
package mm
import (
"unsafe"
"github.com/joetifa2003/mm-go/malloc"
)
func getSize[T any]() int {
var zeroV T
return int(unsafe.Sizeof(zeroV))
}
// Alloc allocates T and returns a pointer to it.
func Alloc[T any]() *T {
ptr := malloc.Malloc(getSize[T]())
return (*T)(unsafe.Pointer(ptr))
}
// FreeMany frees memory allocated by Alloc takes a ptr
// CAUTION: be careful not to double free, and prefer using defer to deallocate
func Free[T any](ptr *T) {
malloc.Free(unsafe.Pointer(ptr))
}
// AllocMany allocates n of T and returns a slice representing the heap.
// CAUTION: don't append to the slice, the purpose of it is to replace pointer
// arithmetic with slice indexing
func AllocMany[T any](n int) []T {
ptr := malloc.Malloc(getSize[T]() * n)
return unsafe.Slice(
(*T)(ptr),
n,
)
}
// FreeMany frees memory allocated by AllocMany takes in the slice (aka the heap)
// CAUTION: be careful not to double free, and prefer using defer to deallocate
func FreeMany[T any](slice []T) {
malloc.Free(unsafe.Pointer(&slice[0]))
}
// Reallocate reallocates memory allocated with AllocMany and doesn't change underling data
func Reallocate[T any](slice []T, newN int) []T {
ptr := malloc.Realloc(unsafe.Pointer(&slice[0]), getSize[T]()*newN)
return unsafe.Slice(
(*T)(ptr),
newN,
)
}