Shrink the webassembly binary down to a reasonable size; TODO actually test it out

This commit is contained in:
Kelvin Ly 2023-05-12 04:35:10 -04:00
parent 55b04efa85
commit febec0cf10
2 changed files with 44 additions and 9 deletions
wordle_opt

View File

@ -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

View File

@ -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<Vec<u8>> = None;
static mut STRINGS: Option<Vec<u8>> = None;
static mut STR_IDXS: Option<Vec<*const c_char>> = 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<T>(v: Option<T>) -> T {
match v {
Some(v) => v,
None => std::process::abort(),
}
}
unsafe fn alloc_ary<T>(sz: usize) -> &'static mut [T] {
let layout = unwrap_or_abort(Layout::from_size_align(
sz*std::mem::size_of::<T>(),
std::mem::align_of::<T>()
).ok());
let ptr = alloc(layout) as *mut T;
std::slice::from_raw_parts_mut(ptr, sz)
}
unsafe fn dealloc_ary<T>(v: &'static mut [T]) {
let layout = unwrap_or_abort(Layout::from_size_align(
v.len()*std::mem::size_of::<T>(),
std::mem::align_of::<T>()
).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))
}
}