diff options
| author | Henry Gressmann <mail@henrygressmann.de> | 2024-01-26 18:03:59 +0100 |
|---|---|---|
| committer | Henry Gressmann <mail@henrygressmann.de> | 2024-01-26 18:03:59 +0100 |
| commit | 8adce672578683dcc7ab62e5492e0f5dbc07a0b4 (patch) | |
| tree | eda57b01f206faf5bcfb7ee70c24fd7be8546e66 /examples/rust/src | |
| parent | 6fd283b06c4912f5d3408b2072cbc3c4e195a236 (diff) | |
docs: string example
Signed-off-by: Henry Gressmann <mail@henrygressmann.de>
Diffstat (limited to 'examples/rust/src')
| -rw-r--r-- | examples/rust/src/hello.rs | 30 | ||||
| -rw-r--r-- | examples/rust/src/print.rs | 18 | ||||
| -rw-r--r-- | examples/rust/src/tinywasm.rs | 2 |
3 files changed, 39 insertions, 11 deletions
diff --git a/examples/rust/src/hello.rs b/examples/rust/src/hello.rs index 34f3c7f..6bb6d97 100644 --- a/examples/rust/src/hello.rs +++ b/examples/rust/src/hello.rs @@ -1,18 +1,28 @@ -#![no_std] #![no_main] -#[cfg(not(test))] -#[panic_handler] -fn panic(_info: &core::panic::PanicInfo) -> ! { - core::arch::wasm32::unreachable() -} - #[link(wasm_import_module = "env")] extern "C" { - fn printi32(x: i32); + fn print_utf8(location: i32, len: i32); +} + +const ARG: &[u8] = &[0u8; 100]; + +#[no_mangle] +pub unsafe extern "C" fn arg_ptr() -> i32 { + ARG.as_ptr() as i32 } #[no_mangle] -pub unsafe extern "C" fn add_and_print(lh: i32, rh: i32) { - printi32(lh + rh); +pub unsafe extern "C" fn arg_size() -> i32 { + ARG.len() as i32 +} + +#[no_mangle] +pub unsafe extern "C" fn hello(len: i32) { + let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap(); + let res = format!("Hello, {}!", arg).as_bytes().to_vec(); + + let len = res.len() as i32; + let ptr = res.leak().as_ptr() as i32; + print_utf8(ptr, len); } diff --git a/examples/rust/src/print.rs b/examples/rust/src/print.rs new file mode 100644 index 0000000..34f3c7f --- /dev/null +++ b/examples/rust/src/print.rs @@ -0,0 +1,18 @@ +#![no_std] +#![no_main] + +#[cfg(not(test))] +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + core::arch::wasm32::unreachable() +} + +#[link(wasm_import_module = "env")] +extern "C" { + fn printi32(x: i32); +} + +#[no_mangle] +pub unsafe extern "C" fn add_and_print(lh: i32, rh: i32) { + printi32(lh + rh); +} diff --git a/examples/rust/src/tinywasm.rs b/examples/rust/src/tinywasm.rs index 0fb9261..08c8135 100644 --- a/examples/rust/src/tinywasm.rs +++ b/examples/rust/src/tinywasm.rs @@ -12,7 +12,7 @@ pub extern "C" fn hello() { } fn run() -> tinywasm::Result<()> { - let module = tinywasm::Module::parse_bytes(include_bytes!("../out/hello.wasm"))?; + let module = tinywasm::Module::parse_bytes(include_bytes!("../out/print.wasm"))?; let mut store = tinywasm::Store::default(); let mut imports = tinywasm::Imports::new(); |
