feat: add __internal/memory

This commit is contained in:
2023-01-19 22:19:54 +08:00
parent 6e4277a53b
commit 137e04eda0
5 changed files with 60 additions and 1 deletions

7
__internal/memory/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "memory"
version = "0.1.0"

View File

@@ -0,0 +1,8 @@
[package]
name = "memory"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,3 @@
Reference:
* https://radu-matei.com/blog/practical-guide-to-wasm-memory/

View File

@@ -0,0 +1,39 @@
#[no_mangle]
pub fn malloc_1(len: usize) -> *mut u8 {
let mut buf = Vec::with_capacity(len);
let ptr = buf.as_mut_ptr();
std::mem::forget(buf);
return ptr;
}
#[no_mangle]
pub fn free_1(ptr: *mut u8, len: usize) {
let data = unsafe { Vec::from_raw_parts(ptr, len, len) };
std::mem::drop(data);
}
#[no_mangle]
pub fn malloc_2(len: usize) -> *mut u8 {
let align = std::mem::align_of::<usize>();
let layout = unsafe { std::alloc::Layout::from_size_align_unchecked(len, align) };
unsafe { std::alloc::alloc(layout) }
}
#[no_mangle]
pub fn free_2(ptr: *mut u8, len: usize) {
let align = std::mem::align_of::<usize>();
let layout = unsafe { std::alloc::Layout::from_size_align_unchecked(len, align) };
unsafe { std::alloc::dealloc(ptr, layout) }
}
fn main() {
println!("Malloc-1");
let p = malloc_1(1024);
println!("Free-1");
free_1(p, 1024);
println!("Malloc-2");
let p = malloc_2(1024);
println!("Free-2");
free_2(p, 1024);
}