v / vlib / dlmalloc / global.v
62 lines · 55 sloc · 1.32 KB · 615e74d341f5936ebd1a95f179247d918ba502b3
Raw
1@[has_globals]
2module 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]
10pub fn malloc(size usize) voidptr {
11 unsafe {
12 return global.malloc(size)
13 }
14}
15
16// free deallocates a `ptr`.
17@[unsafe]
18pub 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]
27pub 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]
41pub 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]
54pub 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