From bd9ac78d1ec27fd4d301084e9fe30b75c0afe854 Mon Sep 17 00:00:00 2001 From: Mikkel ALMONTE--RINGAUD Date: Sat, 28 Dec 2024 15:25:38 +0100 Subject: [PATCH] feat(wasm): add `setup_allocator` macro for optimize the binary a bit --- wasm/README.md | 12 ++++++++++++ wasm/src/lib.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/wasm/README.md b/wasm/README.md index b26b5c1..7b9dedb 100644 --- a/wasm/README.md +++ b/wasm/README.md @@ -7,10 +7,22 @@ wasm = { git = "https://github.com/LiterateInk/Utilities" } wasm-bindgen = "0.2" # required for the `wasm_bindgen::prelude::wasm_bindgen` macro js-sys = "0.3" # required for the `js_sys::Function` type +wee_alloc = "0.4" # required when using `setup_allocator!()` ``` ## Usage +### `setup_allocator` + +```rust +#[cfg(target_arch = "wasm32")] +wasm::setup_allocator!(); +``` + +Will use the `wee_alloc` crate to set up a global allocator for the `wasm32` target. + +### `api_method` + ```rust #[cfg_attr(target_arch = "wasm32", wasm::api_method)] pub async fn fetch_github(something: String) -> String { diff --git a/wasm/src/lib.rs b/wasm/src/lib.rs index 398c9b4..4e0a85a 100644 --- a/wasm/src/lib.rs +++ b/wasm/src/lib.rs @@ -29,3 +29,15 @@ pub fn api_method(_args: TokenStream, input: TokenStream) -> TokenStream { TokenStream::from(output) } + +#[proc_macro] +pub fn setup_allocator(_input: TokenStream) -> TokenStream { + let expanded = quote! { + extern crate wee_alloc; + + #[global_allocator] + static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; + }; + + TokenStream::from(expanded) +}