use std::cell::Cell;
use std::marker::PhantomData;
use std::ops::Deref;
use js::context::JSContext as SafeJSContext;
use js::jsapi::JSContext as RawJSContext;
use js::realm::{AutoRealm, CurrentRealm};
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct JSContext(*mut RawJSContext);
impl From<&mut SafeJSContext> for JSContext {
fn from(safe_cx: &mut SafeJSContext) -> Self {
unsafe { JSContext(safe_cx.raw_cx()) }
}
}
impl<'a> From<&mut CurrentRealm<'a>> for JSContext {
fn from(safe_cx: &mut CurrentRealm<'a>) -> Self {
unsafe { JSContext(safe_cx.raw_cx()) }
}
}
impl<'a> From<&mut AutoRealm<'a>> for JSContext {
fn from(safe_cx: &mut AutoRealm<'a>) -> Self {
unsafe { JSContext(safe_cx.raw_cx()) }
}
}
#[expect(unsafe_code)]
impl JSContext {
pub unsafe fn from_ptr(raw_js_context: *mut RawJSContext) -> Self {
JSContext(raw_js_context)
}
pub fn raw_cx(&self) -> *mut RawJSContext {
self.0
}
pub fn raw_cx_no_gc(&self) -> *mut RawJSContext {
self.0
}
}
impl Deref for JSContext {
type Target = *mut RawJSContext;
fn deref(&self) -> &Self::Target {
&self.0
}
}
thread_local!(
static THREAD_ACTIVE: Cell<bool> = const { Cell::new(true) };
);
pub fn runtime_is_alive() -> bool {
THREAD_ACTIVE.with(|t| t.get())
}
pub fn mark_runtime_dead() {
THREAD_ACTIVE.with(|t| t.set(false));
}
pub unsafe fn temp_cx() -> SafeJSContext {
unsafe { SafeJSContext::from_ptr(js::rust::Runtime::get().unwrap()) }
}
#[derive(Clone, Copy, Debug)]
pub struct CanGc(PhantomData<*mut ()>);
impl CanGc {
pub fn deprecated_note() -> CanGc {
CanGc(PhantomData)
}
pub fn from_cx(_cx: &mut SafeJSContext) -> CanGc {
CanGc::deprecated_note()
}
}