-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathalloc.ml
107 lines (86 loc) · 2.01 KB
/
alloc.ml
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
99
100
101
102
103
104
105
106
107
import stdlib.c.cdef
import stdlib.c.cstdlib
import stdlib.debug
import stdlib.alloc.backend
literal("#define ML_ALLOC_GC")
# Indicates whether the gc is active
let _gc_running = false
macro alloc_warn
printf("Allocation defaults to malloc in %s:%s. Consider starting the gc by using alloc_start.\n", fun, file)
end
macro alloc_stop
if _gc_running == false
panic("Cannot stop an already stopped gc.")
end
literal("#undef s_malloc")
literal("#undef s_realloc")
literal("#undef s_free")
literal("#define s_malloc malloc")
literal("#define s_realloc realloc")
literal("#define s_free free")
literal("#include <sdsalloc.h>")
gc_stop(&ml_gc)
_gc_running = false
end
macro alloc_start(_lit)
if _gc_running
panic("Cannot start an already running gc.")
end
literal("#undef s_malloc")
literal("#undef s_realloc")
literal("#undef s_free")
literal("#define s_malloc ml_malloc")
literal("#define s_realloc ml_realloc")
literal("#define s_free ml_free")
literal("#include <sdsalloc.h>")
gc_start(&ml_gc, &_lit)
_gc_running = true
defer alloc_stop
end
fun alloc_size(sz: int64, fill: bool): void*
let ptr = null
if _gc_running
ptr = _malloc(sz)
else
ptr = malloc(sz)
alloc_warn
end
if ptr == null
panic("Allocation failed.")
end
if fill
memset(ptr, 0, sz)
end
ret ptr
end
fun alloc_size(size: int64): void*
ret alloc_size(size, false)
end
macro alloc(_lit)
_lit = alloc_size(size_of(_lit))
end
macro alloc(_lit, _size)
_lit = alloc_size(_size)
end
macro alloc(_lit, _num, _size)
_lit = alloc(_num, _size * _num)
end
macro alloc_zeroed(_lit)
_lit = alloc_size(size_of(_lit), true)
end
macro alloc_zeroed(_lit, _size)
_lit = alloc_size(_size, true)
end
macro dealloc(_lit)
if _gc_running
_lit._free
else
_lit.free
end
_lit = null
end
macro with(_lit, _body)
alloc(_lit)
defer dealloc(_lit)
_body
end