summaryrefslogtreecommitdiff
path: root/examples/rust
diff options
context:
space:
mode:
Diffstat (limited to 'examples/rust')
-rw-r--r--examples/rust/Cargo.toml14
-rw-r--r--examples/rust/README.md5
-rwxr-xr-xexamples/rust/build.sh7
-rw-r--r--examples/rust/src/fibonacci.rs17
-rw-r--r--examples/rust/src/tinywasm.rs2
5 files changed, 41 insertions, 4 deletions
diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml
index 9ff80dc..d557392 100644
--- a/examples/rust/Cargo.toml
+++ b/examples/rust/Cargo.toml
@@ -1,5 +1,8 @@
cargo-features=["per-package-target"]
+# treat this as an independent package
+[workspace]
+
[package]
publish=false
name="rust-wasm-examples"
@@ -16,3 +19,14 @@ path="src/hello.rs"
[[bin]]
name="tinywasm"
path="src/tinywasm.rs"
+
+[[bin]]
+name="fibonacci"
+path="src/fibonacci.rs"
+
+[profile.wasm]
+opt-level="s"
+lto="thin"
+codegen-units=1
+panic="abort"
+inherits="release"
diff --git a/examples/rust/README.md b/examples/rust/README.md
index 8ecac52..1b6be2f 100644
--- a/examples/rust/README.md
+++ b/examples/rust/README.md
@@ -1 +1,4 @@
-# Examples using Rust compiled to WebAssembly
+# WebAssembly Rust Examples
+
+This is a seperate crate that generates WebAssembly from Rust code.
+It is used by the `wasm-rust` example.
diff --git a/examples/rust/build.sh b/examples/rust/build.sh
index 2c8069a..a8c587a 100755
--- a/examples/rust/build.sh
+++ b/examples/rust/build.sh
@@ -1,11 +1,14 @@
#!/usr/bin/env bash
cd "$(dirname "$0")"
-bins=("hello" "tinywasm")
+bins=("hello" "tinywasm" "fibonacci")
exclude_wat=("tinywasm")
-out_dir="../../target/wasm32-unknown-unknown/wasm"
+out_dir="./target/wasm32-unknown-unknown/wasm"
dest_dir="out"
+# ensure out dir exists
+mkdir -p "$dest_dir"
+
for bin in "${bins[@]}"; do
cargo build --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin "$bin"
diff --git a/examples/rust/src/fibonacci.rs b/examples/rust/src/fibonacci.rs
new file mode 100644
index 0000000..7493132
--- /dev/null
+++ b/examples/rust/src/fibonacci.rs
@@ -0,0 +1,17 @@
+#![no_std]
+#![no_main]
+
+#[cfg(not(test))]
+#[panic_handler]
+fn panic(_info: &core::panic::PanicInfo) -> ! {
+ core::arch::wasm32::unreachable()
+}
+
+#[no_mangle]
+// The rust compiler will convert this to an iterative algorithm.
+pub extern "C" fn fibonacci(n: i32) -> i32 {
+ if n <= 1 {
+ return n;
+ }
+ fibonacci(n - 1) + fibonacci(n - 2)
+}
diff --git a/examples/rust/src/tinywasm.rs b/examples/rust/src/tinywasm.rs
index 0f18ab9..0fb9261 100644
--- a/examples/rust/src/tinywasm.rs
+++ b/examples/rust/src/tinywasm.rs
@@ -26,7 +26,7 @@ fn run() -> tinywasm::Result<()> {
)?;
let instance = module.instantiate(&mut store, Some(imports))?;
- let add_and_print = instance.typed_func::<(i32, i32), ()>(&mut store, "add_and_print")?;
+ let add_and_print = instance.exported_func::<(i32, i32), ()>(&mut store, "add_and_print")?;
add_and_print.call(&mut store, (1, 2))?;
Ok(())
}