v / vlib / dlmalloc
Raw file | 63 loc (56 sloc) | 1.31 KB | Latest commit hash ec91de350
1[has_globals]
2module dlmalloc
3
4__global global = new(get_system_allocator())
5
6/// malloc allocates `size` bytes.
7///
8/// Returns a null pointer if allocation fails. Returns a valid pointer
9/// otherwise.
10[unsafe]
11pub fn malloc(size usize) voidptr {
12 unsafe {
13 return global.malloc(size)
14 }
15}
16
17// free deallocates a `ptr`.
18[unsafe]
19pub fn free(ptr voidptr) {
20 unsafe {
21 global.free_(ptr)
22 }
23}
24
25// Same as `malloc`, except if the allocation succeeds it's guaranteed to
26// point to `size` bytes of zeros.
27[unsafe]
28pub fn calloc(size usize) voidptr {
29 unsafe {
30 return global.calloc(size)
31 }
32}
33
34// realloc reallocates `ptr`, a previous allocation with `old_size` and
35// to have `new_size`.
36//
37//
38// Returns a null pointer if the memory couldn't be reallocated, but `ptr`
39// is still valid. Returns a valid pointer and frees `ptr` if the request
40// is satisfied.
41[unsafe]
42pub fn realloc(ptr voidptr, oldsize usize, newsize usize) voidptr {
43 unsafe {
44 _ := oldsize
45
46 return global.realloc(ptr, newsize)
47 }
48}
49
50// memalign allocates `size` bytes with `align` align.
51//
52//
53// Returns a null pointer if allocation fails. Returns a valid pointer otherwise.
54[unsafe]
55pub fn memalign(size usize, align usize) voidptr {
56 unsafe {
57 if align <= malloc_alignment() {
58 return global.malloc(size)
59 } else {
60 return global.memalign(align, size)
61 }
62 }
63}