script/dom/bindings/conversions.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Conversions of Rust values to and from `JSVal`.
6//!
7//! | IDL type | Argument type | Return type |
8//! |-------------------------|-----------------|----------------|
9//! | any | `JSVal` | |
10//! | boolean | `bool` | |
11//! | byte | `i8` | |
12//! | octet | `u8` | |
13//! | short | `i16` | |
14//! | unsigned short | `u16` | |
15//! | long | `i32` | |
16//! | unsigned long | `u32` | |
17//! | long long | `i64` | |
18//! | unsigned long long | `u64` | |
19//! | unrestricted float | `f32` | |
20//! | float | `Finite<f32>` | |
21//! | unrestricted double | `f64` | |
22//! | double | `Finite<f64>` | |
23//! | DOMString | `DOMString` | |
24//! | USVString | `USVString` | |
25//! | ByteString | `ByteString` | |
26//! | object | `*mut JSObject` | |
27//! | interface types | `&T` | `DomRoot<T>` |
28//! | dictionary types | `&T` | *unsupported* |
29//! | enumeration types | `T` | |
30//! | callback function types | `Rc<T>` | |
31//! | nullable types | `Option<T>` | |
32//! | sequences | `Vec<T>` | |
33//! | union types | `T` | |
34
35use js::context::JSContext;
36pub(crate) use js::conversions::{
37 ConversionBehavior, ConversionResult, FromJSValConvertible, ToJSValConvertible,
38};
39use js::jsapi::JSObject;
40use js::rust::HandleObject;
41pub(crate) use script_bindings::conversions::{is_dom_proxy, *};
42use script_bindings::reflector::DomObject;
43
44use crate::dom::bindings::root::DomRoot;
45
46/// Get a `DomRoot<T>` for the given DOM object, unwrapping any wrapper
47/// around it first, and checking if the object is of the correct type.
48///
49/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is
50/// not a reflector for a DOM object of the given type (as defined by the
51/// proto_id and proto_depth).
52pub(crate) fn root_from_object_static<T>(obj: *mut JSObject) -> Result<DomRoot<T>, ()>
53where
54 T: DomObject + IDLInterface,
55{
56 unsafe { native_from_object_static(obj).map(|ptr| DomRoot::from_ref(&*ptr)) }
57}
58
59/// Get a `DomRoot<T>` for a DOM object accessible from a `HandleObject`.
60pub(crate) fn root_from_handleobject<T>(
61 cx: &mut JSContext,
62 obj: HandleObject,
63) -> Result<DomRoot<T>, ()>
64where
65 T: DomObject + IDLInterface,
66{
67 unsafe { root_from_object(cx, obj.get()) }
68}