diff --git a/crates/cli-support/src/js/mod.rs b/crates/cli-support/src/js/mod.rs index 9bfd47d8..2e9a0a81 100644 --- a/crates/cli-support/src/js/mod.rs +++ b/crates/cli-support/src/js/mod.rs @@ -300,6 +300,15 @@ impl<'a> Context<'a> { ")) })?; + self.bind("__wbindgen_jsval_eq", &|me| { + me.expose_get_object(); + Ok(String::from(" + function(a, b) { + return getObject(a) === getObject(b) ? 1 : 0; + } + ")) + })?; + self.unexport_unused_internal_exports(); self.gc()?; diff --git a/src/lib.rs b/src/lib.rs index ab2e4c7e..055e7e3b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -243,6 +243,14 @@ impl JsValue { } } +impl PartialEq for JsValue { + fn eq(&self, other: &JsValue) -> bool { + unsafe { + __wbindgen_jsval_eq(self.idx, other.idx) != 0 + } + } +} + impl<'a> From<&'a str> for JsValue { fn from(s: &'a str) -> JsValue { JsValue::from_str(s) @@ -317,6 +325,7 @@ externs! { fn __wbindgen_json_parse(ptr: *const u8, len: usize) -> u32; fn __wbindgen_json_serialize(idx: u32, ptr: *mut *mut u8) -> usize; + fn __wbindgen_jsval_eq(a: u32, b: u32) -> u32; } impl Clone for JsValue { diff --git a/tests/all/api.rs b/tests/all/api.rs index 351414c9..a385a46d 100644 --- a/tests/all/api.rs +++ b/tests/all/api.rs @@ -142,3 +142,41 @@ fn works() { .test(); } +#[test] +fn eq_works() { + project() + .file("src/lib.rs", r#" + #![feature(proc_macro, wasm_custom_section)] + + extern crate wasm_bindgen; + + use wasm_bindgen::prelude::*; + + #[wasm_bindgen] + pub fn test(a: &JsValue, b: &JsValue) -> bool { + a == b + } + + #[wasm_bindgen] + pub fn test1(a: &JsValue) -> bool { + a == a + } + "#) + .file("test.ts", r#" + import * as assert from "assert"; + import * as wasm from "./out"; + + export function test() { + assert.strictEqual(wasm.test('a', 'a'), true); + assert.strictEqual(wasm.test('a', 'b'), false); + assert.strictEqual(wasm.test(NaN, NaN), false); + assert.strictEqual(wasm.test({a: 'a'}, {a: 'a'}), false); + assert.strictEqual(wasm.test1(NaN), false); + let x = {a: 'a'}; + assert.strictEqual(wasm.test(x, x), true); + assert.strictEqual(wasm.test1(x), true); + } + "#) + .test(); +} +