Merge pull request #399 from alexcrichton/jsvalue-debug

Implement `Debug for JsValue`
This commit is contained in:
Marcin Baraniecki 2018-07-06 13:36:17 +02:00 committed by GitHub
commit 83a7d5bfdc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 0 deletions

View File

@ -17,6 +17,7 @@ extern crate serde_json;
extern crate wasm_bindgen_macro;
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::Deref;
use core::ptr;
@ -363,6 +364,33 @@ impl Clone for JsValue {
}
}
impl fmt::Debug for JsValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(n) = self.as_f64() {
return n.fmt(f)
}
#[cfg(feature = "std")]
{
if let Some(n) = self.as_string() {
return n.fmt(f)
}
}
if let Some(n) = self.as_bool() {
return n.fmt(f)
}
if self.is_null() {
return fmt::Display::fmt("null", f)
}
if self.is_undefined() {
return fmt::Display::fmt("undefined", f)
}
if self.is_symbol() {
return fmt::Display::fmt("Symbol(..)", f)
}
fmt::Display::fmt("[object]", f)
}
}
impl Drop for JsValue {
fn drop(&mut self) {
unsafe {

View File

@ -76,6 +76,7 @@ fn works() {
c: &JsValue,
) {
assert_eq!(a.as_bool(), Some(true));
assert_eq!(format!("{:?}", a), "true");
assert_eq!(b.as_bool(), Some(false));
assert_eq!(c.as_bool(), None);
}
@ -84,6 +85,7 @@ fn works() {
pub fn mk_symbol() -> JsValue {
let a = JsValue::symbol(None);
assert!(a.is_symbol());
assert_eq!(format!("{:?}", a), "Symbol(..)");
return a
}
@ -103,6 +105,7 @@ fn works() {
#[wasm_bindgen]
pub fn acquire_string(a: &JsValue, b: &JsValue) {
assert_eq!(a.as_string().unwrap(), "foo");
assert_eq!(format!("{:?}", a), "\"foo\"");
assert_eq!(b.as_string(), None);
}