script_bindings/
realms.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 js::jsapi::{GetCurrentRealmOrNull, JSAutoRealm};
6
7use crate::DomTypes;
8use crate::interfaces::GlobalScopeHelpers;
9use crate::reflector::DomObject;
10use crate::script_runtime::JSContext;
11
12pub struct AlreadyInRealm(());
13
14impl AlreadyInRealm {
15    #![allow(unsafe_code)]
16    pub fn assert<D: DomTypes>() -> AlreadyInRealm {
17        unsafe {
18            assert!(!GetCurrentRealmOrNull(*D::GlobalScope::get_cx()).is_null());
19        }
20        AlreadyInRealm(())
21    }
22
23    pub fn assert_for_cx(cx: JSContext) -> AlreadyInRealm {
24        unsafe {
25            assert!(!GetCurrentRealmOrNull(*cx).is_null());
26        }
27        AlreadyInRealm(())
28    }
29}
30
31#[derive(Clone, Copy)]
32pub enum InRealm<'a> {
33    Already(&'a AlreadyInRealm),
34    Entered(&'a JSAutoRealm),
35}
36
37impl<'a> From<&'a AlreadyInRealm> for InRealm<'a> {
38    fn from(token: &'a AlreadyInRealm) -> InRealm<'a> {
39        InRealm::already(token)
40    }
41}
42
43impl<'a> From<&'a JSAutoRealm> for InRealm<'a> {
44    fn from(token: &'a JSAutoRealm) -> InRealm<'a> {
45        InRealm::entered(token)
46    }
47}
48
49impl InRealm<'_> {
50    pub fn already(token: &AlreadyInRealm) -> InRealm<'_> {
51        InRealm::Already(token)
52    }
53
54    pub fn entered(token: &JSAutoRealm) -> InRealm<'_> {
55        InRealm::Entered(token)
56    }
57}
58
59pub fn enter_realm<D: DomTypes>(object: &impl DomObject) -> JSAutoRealm {
60    JSAutoRealm::new(
61        *D::GlobalScope::get_cx(),
62        object.reflector().get_jsobject().get(),
63    )
64}