mirror of
https://github.com/penpot/penpot.git
synced 2025-05-18 13:06:11 +02:00
✨ Use a static Vec<u8> to handle shared memory
This commit is contained in:
parent
df6727f186
commit
6623963a7f
3 changed files with 24 additions and 20 deletions
|
@ -1,17 +1,25 @@
|
|||
static mut BUFFERU8: Option<Box<Vec<u8>>> = None;
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn alloc_bytes(len: usize) -> *mut u8 {
|
||||
// create a new mutable buffer with capacity `len`
|
||||
let mut buf: Vec<u8> = Vec::with_capacity(len);
|
||||
let ptr = buf.as_mut_ptr();
|
||||
// take ownership of the memory block and ensure the its destructor is not
|
||||
// called when the object goes out of scope at the end of the function
|
||||
std::mem::forget(buf);
|
||||
// TODO: Figure out how to deal with Result<T> from Emscripten
|
||||
if unsafe { BUFFERU8.is_some() } {
|
||||
panic!("Bytes already allocated");
|
||||
}
|
||||
|
||||
let mut buffer = Box::new(Vec::<u8>::with_capacity(len));
|
||||
let ptr = buffer.as_mut_ptr();
|
||||
|
||||
unsafe { BUFFERU8 = Some(buffer) };
|
||||
return ptr;
|
||||
}
|
||||
|
||||
pub fn free(ptr: *mut u8, len: usize) {
|
||||
unsafe {
|
||||
let buf = Vec::<u8>::from_raw_parts(ptr, len, len);
|
||||
std::mem::forget(buf);
|
||||
}
|
||||
pub fn free_bytes() {
|
||||
let buffer = unsafe { BUFFERU8.take() }.expect("uninitialized buffer");
|
||||
std::mem::drop(buffer);
|
||||
}
|
||||
|
||||
pub fn buffer_ptr() -> *mut u8 {
|
||||
let buffer = unsafe { BUFFERU8.as_mut() }.expect("uninitializied buffer");
|
||||
buffer.as_mut_ptr()
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue