From ab6abea6a71f0a5be24d3fbfac123131047ae9c5 Mon Sep 17 00:00:00 2001 From: Eric House Date: Tue, 23 Feb 2021 11:16:15 -0800 Subject: [PATCH] use a callback instead of malloc inside js --- xwords4/wasm/main.c | 3 --- xwords4/wasm/wasmasm.c | 48 ++++++++++++++++++++++++------------------ xwords4/wasm/wasmasm.h | 2 ++ 3 files changed, 29 insertions(+), 24 deletions(-) diff --git a/xwords4/wasm/main.c b/xwords4/wasm/main.c index cc6c7f7de..631823cd2 100644 --- a/xwords4/wasm/main.c +++ b/xwords4/wasm/main.c @@ -99,9 +99,6 @@ static void ensureName( GameState* gs ); static void loadName( GameState* gs ); static void saveName( GameState* gs ); - -typedef void (*StringProc)(void* closure, const char* str); - EM_JS(void, show_name, (const char* name), { let jsname = UTF8ToString(name); document.getElementById('gamename').textContent = jsname; diff --git a/xwords4/wasm/wasmasm.c b/xwords4/wasm/wasmasm.c index 1a095a4f6..6a11b37bd 100644 --- a/xwords4/wasm/wasmasm.c +++ b/xwords4/wasm/wasmasm.c @@ -24,16 +24,12 @@ #include "wasmasm.h" #include "comtypes.h" -EM_JS(const char*, _get_stored_value, (const char* key), { +EM_JS(void, _get_stored_value, (const char* key, + StringProc proc, void* closure), { var result = null; var jsKey = UTF8ToString(key); - var jsString = localStorage.getItem(jsKey); - if ( jsString != null ) { - var lengthBytes = lengthBytesUTF8(jsString)+1; - result = _malloc(lengthBytes); - stringToUTF8(jsString, result, lengthBytes); - } - return result; + var val = localStorage.getItem(jsKey); + ccallString(proc, closure, val); }); EM_JS(void, set_stored_value, (const char* key, const char* val), { @@ -54,20 +50,30 @@ EM_JS(bool, have_stored_value, (const char* key), { return result; }); +typedef struct _ValState { + void* ptr; + size_t** len; + bool success; +} ValState; + +static void +onGotVal(void* closure, const char* val) +{ + if ( !!val ) { + ValState* vs = (ValState*)closure; + size_t slen = 1 + strlen(val); + if ( !!vs->ptr && slen <= **vs->len ) { + memcpy( vs->ptr, val, slen ); + vs->success = true; + } + **vs->len = slen; + } +} + bool get_stored_value( const char* key, char out[], size_t* len ) { - bool success = false; - const char* tmp = _get_stored_value( key ); - if ( !!tmp ) { - size_t slen = 1 + strlen(tmp); - if ( !!out && slen <= *len ) { - memcpy( out, tmp, slen ); - success = true; - } - *len = slen; - free( (void*)tmp ); - } - - return success; + ValState state = { .ptr = out, .len = &len, .success = false, }; + _get_stored_value( key, onGotVal, &state ); + return state.success; } diff --git a/xwords4/wasm/wasmasm.h b/xwords4/wasm/wasmasm.h index c6fd28327..a46a32865 100644 --- a/xwords4/wasm/wasmasm.h +++ b/xwords4/wasm/wasmasm.h @@ -23,6 +23,8 @@ #include #include +typedef void (*StringProc)(void* closure, const char* str); + void set_stored_value(const char* key, const char* val); bool get_stored_value(const char* key, char out[], size_t* len); void remove_stored_value(const char* key);