script/dom/
promisenativehandler.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
5use dom_struct::dom_struct;
6use js::realm::CurrentRealm;
7use js::rust::HandleValue;
8use malloc_size_of::MallocSizeOf;
9
10use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
11use crate::dom::bindings::root::DomRoot;
12use crate::dom::bindings::trace::JSTraceable;
13use crate::dom::globalscope::GlobalScope;
14use crate::script_runtime::CanGc;
15
16/// Types that implement the `Callback` trait follow the same rooting requirements
17/// as types that use the `#[dom_struct]` attribute.
18/// Prefer storing `Dom<T>` members inside them instead of `DomRoot<T>`
19/// to minimize redundant work by the garbage collector.
20pub(crate) trait Callback: JSTraceable + MallocSizeOf {
21    fn callback(&self, cx: &mut CurrentRealm, v: HandleValue);
22}
23
24#[dom_struct]
25pub(crate) struct PromiseNativeHandler {
26    reflector: Reflector,
27    resolve: Option<Box<dyn Callback>>,
28    reject: Option<Box<dyn Callback>>,
29}
30
31impl PromiseNativeHandler {
32    pub(crate) fn new(
33        global: &GlobalScope,
34        resolve: Option<Box<dyn Callback>>,
35        reject: Option<Box<dyn Callback>>,
36        can_gc: CanGc,
37    ) -> DomRoot<PromiseNativeHandler> {
38        reflect_dom_object(
39            Box::new(PromiseNativeHandler {
40                reflector: Reflector::new(),
41                resolve,
42                reject,
43            }),
44            global,
45            can_gc,
46        )
47    }
48
49    fn callback(callback: &Option<Box<dyn Callback>>, cx: &mut CurrentRealm, v: HandleValue) {
50        if let Some(ref callback) = *callback {
51            callback.callback(cx, v)
52        }
53    }
54
55    pub(crate) fn resolved_callback(&self, cx: &mut CurrentRealm, v: HandleValue) {
56        PromiseNativeHandler::callback(&self.resolve, cx, v)
57    }
58
59    pub(crate) fn rejected_callback(&self, cx: &mut CurrentRealm, v: HandleValue) {
60        PromiseNativeHandler::callback(&self.reject, cx, v)
61    }
62}