script_bindings/
script_runtime.rs1use std::cell::Cell;
6use std::marker::PhantomData;
7use std::ops::Deref;
8
9use js::context::JSContext as SafeJSContext;
10use js::jsapi::JSContext as RawJSContext;
11use js::realm::{AutoRealm, CurrentRealm};
12
13#[derive(Clone, Copy)]
14#[repr(transparent)]
15pub struct JSContext(*mut RawJSContext);
16
17impl From<&mut SafeJSContext> for JSContext {
18 fn from(safe_cx: &mut SafeJSContext) -> Self {
19 unsafe { JSContext(safe_cx.raw_cx()) }
20 }
21}
22
23impl<'a> From<&mut CurrentRealm<'a>> for JSContext {
24 fn from(safe_cx: &mut CurrentRealm<'a>) -> Self {
25 unsafe { JSContext(safe_cx.raw_cx()) }
26 }
27}
28
29impl<'a> From<&mut AutoRealm<'a>> for JSContext {
30 fn from(safe_cx: &mut AutoRealm<'a>) -> Self {
31 unsafe { JSContext(safe_cx.raw_cx()) }
32 }
33}
34
35#[expect(unsafe_code)]
36impl JSContext {
37 pub unsafe fn from_ptr(raw_js_context: *mut RawJSContext) -> Self {
43 JSContext(raw_js_context)
44 }
45
46 pub fn raw_cx(&self) -> *mut RawJSContext {
48 self.0
49 }
50
51 pub fn raw_cx_no_gc(&self) -> *mut RawJSContext {
53 self.0
54 }
55}
56
57impl Deref for JSContext {
58 type Target = *mut RawJSContext;
59
60 fn deref(&self) -> &Self::Target {
61 &self.0
62 }
63}
64
65thread_local!(
66 static THREAD_ACTIVE: Cell<bool> = const { Cell::new(true) };
67);
68
69pub fn runtime_is_alive() -> bool {
70 THREAD_ACTIVE.with(|t| t.get())
71}
72
73pub fn mark_runtime_dead() {
74 THREAD_ACTIVE.with(|t| t.set(false));
75}
76
77pub unsafe fn temp_cx() -> SafeJSContext {
86 unsafe { SafeJSContext::from_ptr(js::rust::Runtime::get().unwrap()) }
87}
88
89#[derive(Clone, Copy, Debug)]
90pub struct CanGc(PhantomData<*mut ()>);
96
97impl CanGc {
98 pub fn note() -> CanGc {
101 CanGc(PhantomData)
102 }
103
104 pub fn from_cx(_cx: &mut SafeJSContext) -> CanGc {
106 CanGc::note()
107 }
108}