web3api_wasm_rs/malloc.rs
1/// Allocate memory into the module's linear memory
2/// and return the offset to the start of the block.
3#[no_mangle]
4pub fn alloc(len: usize) -> *mut u8 {
5 // create a new mutable buffer with capacity `len`
6 let mut buf = Vec::with_capacity(len);
7 // take a mutable pointer to the buffer
8 let ptr = buf.as_mut_ptr();
9 // take ownership of the memory block and
10 // ensure the its destructor is not
11 // called when the object goes out of scope
12 // at the end of the function
13 std::mem::forget(buf);
14 // return the pointer so the runtime
15 // can write data at this offset
16 ptr
17}
18
19#[no_mangle]
20pub unsafe fn dealloc(ptr: *mut u8, size: usize) {
21 let data = Vec::from_raw_parts(ptr, size, size);
22 std::mem::drop(data);
23}