-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
67 lines (59 loc) · 2.3 KB
/
Copy pathlib.rs
File metadata and controls
67 lines (59 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! Convert JS-imported reference types to Rust-exported types.
#![cfg_attr(not(feature = "std"), no_std)]
use wasm_bindgen::{JsCast, JsValue};
/// Convert from a JS-imported reference type to a Rust-exported type.
///
/// Implement this trait to enable conversion from a typed JS reference
/// wrapper (generated by `#[wasm_refgen]`) back to the concrete Rust type.
///
/// The default [`try_from_js_value`](FromJsRef::try_from_js_value)
/// implementation uses `dyn_ref` (i.e. `instanceof`). When using
/// `#[wasm_refgen]`, the generated impl overrides this with a duck-type
/// check via `Reflect::has` — prefer `try_from_js_value` over `dyn_into`
/// for `wasm_refgen`-generated types.
pub trait FromJsRef: Sized {
/// The JS-imported reference type (e.g., `JsFoo` generated by `#[wasm_refgen]`).
type JsRef: wasm_bindgen::JsCast;
/// Infallible conversion from a typed JS reference to the Rust type.
fn from_js_ref(castable: &Self::JsRef) -> Self;
/// Fallible conversion from a raw `JsValue`.
///
/// Returns `Some` if the value is the expected type, `None` otherwise.
///
/// The default implementation uses `dyn_ref` (`instanceof`), which does
/// _not_ work for `wasm_refgen`-generated extern types. The generated
/// `FromJsRef` impl overrides this with a duck-type `Reflect::has` check.
#[must_use]
fn try_from_js_value(js_value: &JsValue) -> Option<Self> {
js_value
.dyn_ref::<Self::JsRef>()
.map(|js_ref| Self::from_js_ref(js_ref))
}
}
/// Convenience trait for converting a JS reference to its Rust counterpart.
///
/// This is a blanket-implemented companion to [`FromJsRef`]. Instead of
/// calling `WasmFoo::from_js_ref(&js_foo)`, you can call `js_foo.js_deref()`:
///
/// ```ignore
/// use from_js_ref::JsDeref;
///
/// let foo: WasmFoo = js_foo.js_deref();
/// ```
///
/// Automatically available on any `T::JsRef` where `T: FromJsRef`.
pub trait JsDeref<T: FromJsRef> {
/// Convert this JS reference to the corresponding Rust type.
fn js_deref(&self) -> T;
}
impl<T: FromJsRef> JsDeref<T> for T::JsRef {
fn js_deref(&self) -> T {
T::from_js_ref(self)
}
}
/// Re-exports for use by generated code. Not part of the public API.
#[doc(hidden)]
pub mod __private {
pub use js_sys;
pub use wasm_bindgen;
}