script_bindings/script_runtime.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 std::cell::Cell;
6use std::marker::PhantomData;
7use std::ops::Deref;
8
9use js::jsapi::JSContext as RawJSContext;
10
11#[derive(Clone, Copy)]
12#[repr(transparent)]
13pub struct JSContext(*mut RawJSContext);
14
15#[allow(unsafe_code)]
16impl JSContext {
17 /// Create a new [`JSContext`] object from the given raw pointer.
18 ///
19 /// # Safety
20 ///
21 /// The `RawJSContext` argument must point to a valid `RawJSContext` in memory.
22 pub unsafe fn from_ptr(raw_js_context: *mut RawJSContext) -> Self {
23 JSContext(raw_js_context)
24 }
25}
26
27#[allow(unsafe_code)]
28impl Deref for JSContext {
29 type Target = *mut RawJSContext;
30
31 fn deref(&self) -> &Self::Target {
32 &self.0
33 }
34}
35
36thread_local!(
37 static THREAD_ACTIVE: Cell<bool> = const { Cell::new(true) };
38);
39
40pub fn runtime_is_alive() -> bool {
41 THREAD_ACTIVE.with(|t| t.get())
42}
43
44pub fn mark_runtime_dead() {
45 THREAD_ACTIVE.with(|t| t.set(false));
46}
47
48#[derive(Clone, Copy, Debug)]
49/// A compile-time marker that there are operations that could trigger a JS garbage collection
50/// operation within the current stack frame. It is trivially copyable, so it should be passed
51/// as a function argument and reused when calling other functions whenever possible. Since it
52/// is only meaningful within the current stack frame, it is impossible to move it to a different
53/// thread or into a task that will execute asynchronously.
54pub struct CanGc(PhantomData<*mut ()>);
55
56impl CanGc {
57 /// Create a new CanGc value, representing that a GC operation is possible within the
58 /// current stack frame.
59 pub fn note() -> CanGc {
60 CanGc(PhantomData)
61 }
62}