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