|
| 1 | +pub type size_t = usize; |
| 2 | + |
| 3 | +const MALLOC_HEADER : isize = 8; |
| 4 | +const MALLOC_ALIGN : usize = 8; |
| 5 | + |
| 6 | +use super::c_void; |
| 7 | +use std::alloc::{self, Layout}; |
| 8 | +use std::ptr; |
| 9 | + |
| 10 | +pub unsafe fn malloc(size: size_t) -> *mut c_void { |
| 11 | + let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); |
| 12 | + let p = alloc::alloc(lay); |
| 13 | + if p.is_null() { |
| 14 | + return ptr::null_mut(); |
| 15 | + } |
| 16 | + *(p as *mut size_t) = size; |
| 17 | + p.offset(MALLOC_HEADER) as *mut c_void |
| 18 | +} |
| 19 | +pub unsafe fn free(p: *mut c_void) { |
| 20 | + let p = p.offset(-MALLOC_HEADER) as *mut u8; |
| 21 | + let size = *(p as *mut size_t); |
| 22 | + let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); |
| 23 | + alloc::dealloc(p, lay); |
| 24 | +} |
| 25 | +pub unsafe fn realloc(p: *mut c_void, _size: size_t) -> *mut c_void { |
| 26 | + let p = p.offset(-MALLOC_HEADER) as *mut u8; |
| 27 | + let size = *(p as *mut size_t); |
| 28 | + let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); |
| 29 | + let p = alloc::realloc(p, lay, size); |
| 30 | + if p.is_null() { |
| 31 | + return ptr::null_mut(); |
| 32 | + } |
| 33 | + *(p as *mut size_t) = size; |
| 34 | + p.offset(MALLOC_HEADER) as *mut c_void |
| 35 | +} |
| 36 | + |
0 commit comments