From febec0cf105023a8a90a9b8ffefe0e8010a999fa Mon Sep 17 00:00:00 2001 From: Kelvin Ly Date: Fri, 12 May 2023 04:35:10 -0400 Subject: [PATCH] Shrink the webassembly binary down to a reasonable size; TODO actually test it out --- wordle_opt/Cargo.toml | 2 +- wordle_opt/src/lib.rs | 51 ++++++++++++++++++++++++++++++++++++------- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/wordle_opt/Cargo.toml b/wordle_opt/Cargo.toml index b287053..0fcfdb6 100644 --- a/wordle_opt/Cargo.toml +++ b/wordle_opt/Cargo.toml @@ -8,8 +8,8 @@ crate-type = ["cdylib"] bench = false [profile.release] -debug = true lto = true +opt-level = 's' # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/wordle_opt/src/lib.rs b/wordle_opt/src/lib.rs index 907913d..e333eb4 100644 --- a/wordle_opt/src/lib.rs +++ b/wordle_opt/src/lib.rs @@ -1,22 +1,52 @@ +use std::alloc::{alloc, dealloc, Layout}; + extern crate wee_alloc; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; - // webassembly version of all the wordle logic // because the javascript version is slow as hell on firefox use std::os::raw::c_char; -static mut LOOKUP: Option> = None; -static mut STRINGS: Option> = None; -static mut STR_IDXS: Option> = None; +static mut LOOKUP: Option<&'static mut [u8]> = None; +static mut STRINGS: Option<&'static mut [u8]> = None; +static mut STR_IDXS: Option<&'static mut [*const c_char]> = None; + +fn unwrap_or_abort(v: Option) -> T { + match v { + Some(v) => v, + None => std::process::abort(), + } +} + +unsafe fn alloc_ary(sz: usize) -> &'static mut [T] { + let layout = unwrap_or_abort(Layout::from_size_align( + sz*std::mem::size_of::(), + std::mem::align_of::() + ).ok()); + let ptr = alloc(layout) as *mut T; + std::slice::from_raw_parts_mut(ptr, sz) +} + +unsafe fn dealloc_ary(v: &'static mut [T]) { + let layout = unwrap_or_abort(Layout::from_size_align( + v.len()*std::mem::size_of::(), + std::mem::align_of::() + ).ok()); + dealloc(v.as_ptr() as *mut u8, layout); +} + #[no_mangle] pub extern fn init_strings(sz: usize) -> *mut c_char { unsafe { - STRINGS = Some(vec![0u8; sz]); - STRINGS.as_deref_mut().map(|v| v.as_mut_ptr() as *mut c_char).unwrap() + if let Some(v) = &mut STRINGS { + dealloc_ary(v); + STRINGS = None; + } + STRINGS = Some(alloc_ary(sz)); + unwrap_or_abort(STRINGS.as_deref_mut().map(|v| v.as_mut_ptr() as *mut c_char)) } } @@ -30,9 +60,14 @@ pub extern fn init_idx() -> usize { pub extern fn init_lookup() -> *mut c_char { unsafe { let num_strings = STR_IDXS.as_ref().map(|idxs| idxs.len()).unwrap_or(0); + if let Some(v) = &mut LOOKUP { + dealloc_ary(v); + STRINGS = None; + } - LOOKUP = Some(vec![0u8; num_strings*num_strings]); - LOOKUP.as_deref_mut().map(|v| v.as_mut_ptr() as *mut c_char).unwrap() + LOOKUP = Some(alloc_ary(num_strings*num_strings)); + unwrap_or_abort( + LOOKUP.as_deref_mut().map(|v| v.as_mut_ptr() as *mut c_char)) } }