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;
6
7use js::context::JSContext;
8use js::jsapi::JS::{HeapState, RuntimeHeapState};
9
10thread_local!(
11 static THREAD_ACTIVE: Cell<bool> = const { Cell::new(true) };
12);
13
14pub fn runtime_is_alive() -> bool {
15 THREAD_ACTIVE.with(|t| t.get())
16}
17
18/// Whether a GC collection is in progress.
19/// Mainly useful for (debug) assertions.
20pub fn during_gc_collection() -> bool {
21 // SAFETY: `RuntimeHeapState` only reads thread-local runtime state and has no preconditions.
22 matches!(
23 unsafe { RuntimeHeapState() },
24 HeapState::MajorCollecting | HeapState::MinorCollecting
25 )
26}
27
28pub fn mark_runtime_dead() {
29 THREAD_ACTIVE.with(|t| t.set(false));
30}
31
32/// Get the current JSContext for the running thread.
33///
34/// ## Safety
35/// Using this function is unsafe because no other JSContext may be constructed apart from initial ones,
36/// but because we are still working on passing down &mut SafeJSContext references,
37/// this function is provided as temporary workaround/placeholder.
38///
39/// As such all it's usages will need to be eventually replaced with proper &mut SafeJSContext references.
40pub unsafe fn temp_cx() -> JSContext {
41 unsafe { JSContext::from_ptr(js::rust::Runtime::get().unwrap()) }
42}