-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalloc.go
More file actions
57 lines (48 loc) · 1.03 KB
/
alloc.go
File metadata and controls
57 lines (48 loc) · 1.03 KB
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
package vk
// #include <stdlib.h>
import "C"
import (
"runtime"
"unsafe"
"honnef.co/go/safeish"
)
type allocator struct {
allocs []unsafe.Pointer
pinner runtime.Pinner
}
func (a *allocator) free() {
for _, alloc := range a.allocs {
C.free(alloc)
}
a.allocs = nil
a.pinner.Unpin()
}
func pinAsCastedPtr[Dst ~*DstE, Src ~*SrcE, DstE, SrcE any](a *allocator, s Src) Dst {
ptr := safeish.Cast[Dst](s)
a.pinner.Pin(ptr)
return ptr
}
func pinSlice[Src ~[]SrcE, SrcE any](a *allocator, s Src) *SrcE {
if cap(s) == 0 {
return nil
}
ptr := unsafe.SliceData(s)
a.pinner.Pin(ptr)
return ptr
}
func pinSliceAsCastedPtr[Dst ~*DstE, Src ~[]SrcE, DstE, SrcE any](a *allocator, s Src) Dst {
ptr := safeish.SliceCastPtr[Dst](s)
a.pinner.Pin(ptr)
return ptr
}
func alloc[T any](a *allocator) *T {
return allocn[T](a, 1)
}
func allocn[T any](a *allocator, nmemb int) *T {
if nmemb == 0 {
return nil
}
m := (*T)(C.calloc(C.size_t(nmemb), C.size_t(unsafe.Sizeof(*new(T)))))
a.allocs = append(a.allocs, unsafe.Pointer(m))
return m
}