forked from egonelbre/exp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
malloc.go
63 lines (47 loc) · 1.15 KB
/
malloc.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
package mm
import "unsafe"
// #include <stdlib.h>
import "C"
const PlatformAlignment = 4 // todo: add build tags
type Malloc struct{}
func (m Malloc) Alignment() int { return PlatformAlignment }
func (m Malloc) Alloc(size int) unsafe.Pointer {
if size == 0 {
return nil
}
return unsafe.Pointer(C.malloc(C.size_t(size)))
}
func (m Malloc) Dealloc(p unsafe.Pointer) bool {
C.free(p)
return true
}
func (m Malloc) Realloc(p *unsafe.Pointer, size int) bool {
if size == 0 {
m.Dealloc(*p)
*p = nil
return true
}
*p = unsafe.Pointer(C.realloc(*p, C.size_t(size)))
return *p != nil
}
type Aligned struct{}
func (m Aligned) Alignment() int { return PlatformAlignment }
func (m Aligned) Alloc(size int) unsafe.Pointer {
if size == 0 {
return nil
}
return unsafe.Pointer(C._aligned_malloc(C.size_t(size), C.size_t(PlatformAlignment)))
}
func (m Aligned) Dealloc(p unsafe.Pointer) bool {
C._aligned_free(p)
return true
}
func (m Aligned) Realloc(p *unsafe.Pointer, size int) bool {
if size == 0 {
m.Dealloc(*p)
*p = nil
return true
}
*p = unsafe.Pointer(C._aligned_realloc(*p, C.size_t(size), C.size_t(PlatformAlignment)))
return *p != nil
}