From 466477c6cda344a6e33fcad4a00f257d27a4e695 Mon Sep 17 00:00:00 2001 From: aj Date: Sun, 11 Oct 2020 12:17:55 +0100 Subject: [PATCH] adding macro functions --- README.md | 2 +- src/lib.rs | 33 +++++++++++++++++++++++++++++++++ www/index.html | 1 + www/index.js | 5 +++++ www/package.json | 1 - 5 files changed, 40 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4f3a901..f3e3cba 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ wazem Playing with client-side rust libraries for speedy types. * `wasm-pack` -* `create-wasm-app`-bootstraoo dev server +* `create-wasm-app`-start dev server ## Usage diff --git a/src/lib.rs b/src/lib.rs index 6f1066a..34352de 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,30 @@ macro_rules! log { } } +macro_rules! expr_stringer { + // This macro takes an expression of type `expr` and prints + // it as a string along with its result. + // The `expr` designator is used for expressions. + ($expression:expr) => { + // `stringify!` will convert the expression *as it is* into a string. + format!("{:?} = {:?}", stringify!($expression), $expression) + }; + ($expression:literal) => { + format!("{:?} = {:?}", $expression, "Nothing") + }; +} + +macro_rules! find_min { + // Base case: + ($x:expr) => ($x); + // `$x` followed by at least one `$y,` + ($x:expr, $($y:expr),+) => ( + // Call `find_min!` on the tail `$y` + std::cmp::min($x, find_min!($($y),+)) + ) +} + + // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] @@ -26,7 +50,16 @@ pub fn greet() { alert("Hello, Wazem!"); } +#[wasm_bindgen] +pub fn find_min() { + log!("Min (5): {}", find_min!(5u8)); + log!("Min (5/9): {}", find_min!(5u8, 9u8)); + log!("Min (10/6/9): {}", find_min!(10u8, 6u8, 9u8)); +} + #[wasm_bindgen] pub fn test_log() { log!("Hello browser, Love Wazem!"); + log!("{}", expr_stringer!(3 + 5)); + log!("{}", expr_stringer!("a literal")); } diff --git a/www/index.html b/www/index.html index 9500c8d..e41ff8f 100644 --- a/www/index.html +++ b/www/index.html @@ -8,5 +8,6 @@ + diff --git a/www/index.js b/www/index.js index e02bb94..705f580 100644 --- a/www/index.js +++ b/www/index.js @@ -2,9 +2,14 @@ import * as wasm from "wazem"; wasm.test_log(); document.getElementById("clickMe").onclick = OnButtonClick; +document.getElementById("minButton").onclick = OnMinClick; export function OnButtonClick(){ wasm.greet(); } +export function OnMinClick(){ + wasm.find_min(); +} + export default wasm; diff --git a/www/package.json b/www/package.json index 00ff129..a40e71b 100644 --- a/www/package.json +++ b/www/package.json @@ -27,7 +27,6 @@ }, "devDependencies": { "copy-webpack-plugin": "^5.1.2", - "wazem": "^0.1.0", "webpack": "^4.44.2", "webpack-cli": "^3.1.0", "webpack-dev-server": "^3.1.5"