forked from kornelski/lodepng-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This adds a wasm32 implementation for `free`, `malloc` and `realloc`. Originally written by @rodrigorc in rust-lang/libc#1092 and adapted.
- Loading branch information
Showing
2 changed files
with
44 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
pub type size_t = usize; | ||
|
||
const MALLOC_HEADER : isize = 8; | ||
const MALLOC_ALIGN : usize = 8; | ||
|
||
use super::c_void; | ||
use std::alloc::{self, Layout}; | ||
use std::ptr; | ||
|
||
pub unsafe fn malloc(size: size_t) -> *mut c_void { | ||
let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); | ||
let p = alloc::alloc(lay); | ||
if p.is_null() { | ||
return ptr::null_mut(); | ||
} | ||
*(p as *mut size_t) = size; | ||
p.offset(MALLOC_HEADER) as *mut c_void | ||
} | ||
pub unsafe fn free(p: *mut c_void) { | ||
let p = p.offset(-MALLOC_HEADER) as *mut u8; | ||
let size = *(p as *mut size_t); | ||
let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); | ||
alloc::dealloc(p, lay); | ||
} | ||
pub unsafe fn realloc(p: *mut c_void, _size: size_t) -> *mut c_void { | ||
let p = p.offset(-MALLOC_HEADER) as *mut u8; | ||
let size = *(p as *mut size_t); | ||
let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); | ||
let p = alloc::realloc(p, lay, size); | ||
if p.is_null() { | ||
return ptr::null_mut(); | ||
} | ||
*(p as *mut size_t) = size; | ||
p.offset(MALLOC_HEADER) as *mut c_void | ||
} | ||
|