From 54fb81cd3a4927f0a08b48b2a5b0499cdf1d01bc Mon Sep 17 00:00:00 2001 From: Richard Dodd Date: Wed, 9 Jan 2019 17:42:56 +0000 Subject: [PATCH] Use `toString` where `JSON.stringify` didn't work --- crates/cli-support/src/js/mod.rs | 17 +++++++++++++++++ src/lib.rs | 18 +++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/cli-support/src/js/mod.rs b/crates/cli-support/src/js/mod.rs index 33392a2ae5f..428134ff4fc 100644 --- a/crates/cli-support/src/js/mod.rs +++ b/crates/cli-support/src/js/mod.rs @@ -348,6 +348,23 @@ impl<'a> Context<'a> { )) })?; + self.bind("__wbindgen_to_string", &|me| { + me.expose_pass_string_to_wasm()?; + me.expose_get_object(); + me.expose_uint32_memory(); + Ok(String::from( + " + function(i, len_ptr) { + let toString = getObject(i).toString(); + if (typeof(toString) !== 'string') return 0; + const ptr = passStringToWasm(toString); + getUint32Memory()[len_ptr / 4] = WASM_VECTOR_LEN; + return ptr; + } + ", + )) + })?; + self.bind("__wbindgen_cb_drop", &|me| { me.expose_drop_ref(); Ok(String::from( diff --git a/src/lib.rs b/src/lib.rs index be65dd99c46..e507af0e1c8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -313,6 +313,21 @@ impl JsValue { String::from_utf8_unchecked(s) } } + + /// Get the string value of self using the JS `toString` method. + #[cfg(feature = "std")] + fn js_to_string(&self) -> String { + unsafe { + let mut len = 0; + let ptr = __wbindgen_to_string(self.idx, &mut len); + if ptr.is_null() { + unreachable!("Object.toString must return a valid string") + } else { + let data = Vec::from_raw_parts(ptr, len, len); + String::from_utf8_unchecked(data) + } + } + } } impl PartialEq for JsValue { @@ -488,6 +503,7 @@ externs! { fn __wbindgen_is_function(idx: u32) -> u32; fn __wbindgen_is_string(idx: u32) -> u32; fn __wbindgen_string_get(idx: u32, len: *mut usize) -> *mut u8; + fn __wbindgen_to_string(idx: u32, len: *mut usize) -> *mut u8; fn __wbindgen_throw(a: *const u8, b: usize) -> !; fn __wbindgen_rethrow(a: u32) -> !; @@ -539,7 +555,7 @@ impl fmt::Debug for JsValue { } let json = self.as_json(); if json == "{}" { - f.write_str("[object]") + f.write_str(&self.js_to_string()) } else { f.write_str(&json) }