Add has_type and update is_instance_of docs

This commit is contained in:
Ingvar Stepanyan 2019-04-12 17:41:51 +01:00
parent cb880bdbff
commit c77b46af7d

View File

@ -20,6 +20,9 @@ where
///
/// This method performs a dynamic check (at runtime) using the JS
/// `instanceof` operator. This method returns `self instanceof T`.
///
/// Note that `instanceof` does not work with primitive values or across
/// different realms (e.g. iframes). Prefer using `has_type` instead.
fn is_instance_of<T>(&self) -> bool
where
T: JsCast,
@ -27,17 +30,28 @@ where
T::instanceof(self.as_ref())
}
/// Test whether this JS value has a type `T`.
///
/// Unlike `is_instance_of`, the type can override this to a specialised
/// check that works reliably with primitives and across realms.
fn has_type<T>(&self) -> bool
where
T: JsCast,
{
T::is_type_of(self.as_ref())
}
/// Performs a dynamic cast (checked at runtime) of this value into the
/// target type `T`.
///
/// This method will return `Err(self)` if `T::is_type_of(self)`
/// This method will return `Err(self)` if `self.has_type::<T>()`
/// returns `false`, and otherwise it will return `Ok(T)` manufactured with
/// an unchecked cast (verified correct via the `instanceof` operation).
fn dyn_into<T>(self) -> Result<T, Self>
where
T: JsCast,
{
if T::is_type_of(self.as_ref()) {
if self.has_type::<T>() {
Ok(self.unchecked_into())
} else {
Err(self)
@ -47,14 +61,14 @@ where
/// Performs a dynamic cast (checked at runtime) of this value into the
/// target type `T`.
///
/// This method will return `None` if `T::is_type_of(self)`
/// This method will return `None` if `self.has_type::<T>()`
/// returns `false`, and otherwise it will return `Some(&T)` manufactured
/// with an unchecked cast (verified correct via the `instanceof` operation).
fn dyn_ref<T>(&self) -> Option<&T>
where
T: JsCast,
{
if T::is_type_of(self.as_ref()) {
if self.has_type::<T>() {
Some(self.unchecked_ref())
} else {
None
@ -103,7 +117,12 @@ where
/// Performs a dynamic check to see whether the `JsValue` provided
/// is a value of this type.
///
/// Unlike `instanceof`, this can be specialised to use a custom check.
/// Unlike `instanceof`, this can be specialised to use a custom check by
/// adding a `#[wasm_bindgen(is_type_of = callback)]` attribute to the
/// type import declaration.
///
/// Other than that, this is intended to be an internal implementation
/// detail of `has_type` and you likely won't need to call this.
fn is_type_of(val: &JsValue) -> bool {
Self::instanceof(val)
}