Skip to content

Commit

Permalink
Use toString where JSON.stringify didn't work
Browse files Browse the repository at this point in the history
  • Loading branch information
derekdreery committed Jan 9, 2019
1 parent 8e732f2 commit 54fb81c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
17 changes: 17 additions & 0 deletions crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
18 changes: 17 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) -> !;

Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit 54fb81c

Please sign in to comment.