Implement PartialEq for JsValue (#217)

Dispatch to JS's `===` operator internally
This commit is contained in:
Alex Crichton 2018-06-01 16:47:45 -05:00 committed by GitHub
parent cb1e5cf136
commit 659583b40d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 56 additions and 0 deletions

View File

@ -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.unexport_unused_internal_exports();
self.gc()?; self.gc()?;

View File

@ -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 { impl<'a> From<&'a str> for JsValue {
fn from(s: &'a str) -> JsValue { fn from(s: &'a str) -> JsValue {
JsValue::from_str(s) JsValue::from_str(s)
@ -317,6 +325,7 @@ externs! {
fn __wbindgen_json_parse(ptr: *const u8, len: usize) -> u32; fn __wbindgen_json_parse(ptr: *const u8, len: usize) -> u32;
fn __wbindgen_json_serialize(idx: u32, ptr: *mut *mut u8) -> usize; fn __wbindgen_json_serialize(idx: u32, ptr: *mut *mut u8) -> usize;
fn __wbindgen_jsval_eq(a: u32, b: u32) -> u32;
} }
impl Clone for JsValue { impl Clone for JsValue {

View File

@ -142,3 +142,41 @@ fn works() {
.test(); .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();
}