v2 / vlib / builtin / wasm / alloc.v
33 lines · 27 sloc · 786 bytes · d559a62cfe3f3de0a5ca1e59f14e622960e3917b
Raw
1@[has_globals]
2module builtin
3
4// Shitty `sbrk` basic `malloc` and `free` impl
5// TODO: implement pure V `walloc` later
6
7__global g_heap_base = usize(vwasm_heap_base())
8
9// malloc dynamically allocates a `n` bytes block of memory on the heap.
10// malloc returns a `byteptr` pointing to the memory address of the allocated space.
11// unlike the `calloc` family of functions - malloc will not zero the memory block.
12@[unsafe]
13pub fn malloc(n isize) &u8 {
14 if n <= 0 {
15 $if no_imports ? {
16 return unsafe { nil }
17 } $else {
18 panic('malloc(n <= 0)')
19 }
20 }
21
22 res := g_heap_base
23 g_heap_base += usize(n)
24
25 return &u8(res)
26}
27
28// free allows for manually freeing memory allocated at the address `ptr`.
29// currently does not free any memory.
30@[unsafe]
31pub fn free(ptr voidptr) {
32 _ := ptr
33}
34