use std::cell::RefCell;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::{Arc, Weak};
use js::jsapi::JSTracer;
use rustc_hash::FxHashMap;
use script_bindings::script_runtime::CanGc;
use crate::dom::bindings::conversions::ToJSValConvertible;
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::trace::trace_reflector;
use crate::dom::promise::Promise;
use crate::task::TaskOnce;
mod dummy {
use std::cell::RefCell;
use std::rc::Rc;
use rustc_hash::FxHashMap;
use super::LiveDOMReferences;
thread_local!(pub(crate) static LIVE_REFERENCES: Rc<RefCell<LiveDOMReferences>> =
Rc::new(RefCell::new(
LiveDOMReferences {
reflectable_table: RefCell::new(FxHashMap::default()),
promise_table: RefCell::new(FxHashMap::default()),
}
)));
}
pub(crate) use self::dummy::LIVE_REFERENCES;
#[derive(MallocSizeOf)]
struct TrustedReference(
#[ignore_malloc_size_of = "This is a shared reference."] *const libc::c_void,
);
unsafe impl Send for TrustedReference {}
impl TrustedReference {
unsafe fn new(ptr: *const libc::c_void) -> TrustedReference {
TrustedReference(ptr)
}
}
pub struct TrustedPromise {
dom_object: *const Promise,
owner_thread: *const libc::c_void,
}
unsafe impl Send for TrustedPromise {}
impl TrustedPromise {
pub(crate) fn new(promise: Rc<Promise>) -> TrustedPromise {
LIVE_REFERENCES.with(|r| {
let live_references = &*r.borrow();
let ptr = &raw const *promise;
live_references.addref_promise(promise);
TrustedPromise {
dom_object: ptr,
owner_thread: (live_references) as *const _ as *const libc::c_void,
}
})
}
pub(crate) fn root(self) -> Rc<Promise> {
LIVE_REFERENCES.with(|r| {
let live_references = &*r.borrow();
assert_eq!(
self.owner_thread,
live_references as *const _ as *const libc::c_void
);
match live_references
.promise_table
.borrow_mut()
.entry(self.dom_object)
{
Occupied(mut entry) => {
let promise = {
let promises = entry.get_mut();
promises
.pop()
.expect("rooted promise list unexpectedly empty")
};
if entry.get().is_empty() {
entry.remove();
}
promise
},
Vacant(_) => unreachable!(),
}
})
}
pub(crate) fn reject_task(self, error: Error) -> impl TaskOnce {
let this = self;
task!(reject_promise: move |cx| {
debug!("Rejecting promise.");
this.root().reject_error(error, CanGc::from_cx(cx));
})
}
pub(crate) fn resolve_task<T>(self, value: T) -> impl TaskOnce
where
T: ToJSValConvertible + Send,
{
let this = self;
task!(resolve_promise: move |cx| {
debug!("Resolving promise.");
this.root().resolve_native(&value, CanGc::from_cx(cx));
})
}
}
#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
#[derive(MallocSizeOf)]
pub(crate) struct Trusted<T: DomObject> {
#[conditional_malloc_size_of]
refcount: Arc<TrustedReference>,
#[ignore_malloc_size_of = "These are shared by all `Trusted` types."]
owner_thread: *const LiveDOMReferences,
phantom: PhantomData<T>,
}
impl<T: DomObject> std::fmt::Debug for Trusted<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str("...")
}
}
unsafe impl<T: DomObject> Send for Trusted<T> {}
impl<T: DomObject> Trusted<T> {
pub(crate) fn new(ptr: &T) -> Trusted<T> {
fn add_live_reference(
ptr: *const libc::c_void,
) -> (Arc<TrustedReference>, *const LiveDOMReferences) {
LIVE_REFERENCES.with(|r| {
let live_references = &*r.borrow();
let refcount = unsafe { live_references.addref(ptr) };
(refcount, live_references as *const _)
})
}
let (refcount, owner_thread) = add_live_reference(ptr as *const T as *const _);
Trusted {
refcount,
owner_thread,
phantom: PhantomData,
}
}
pub(crate) fn root(&self) -> DomRoot<T> {
fn validate(owner_thread: *const LiveDOMReferences) {
assert!(LIVE_REFERENCES.with(|r| {
let r = r.borrow();
let live_references = &*r;
owner_thread == live_references
}));
}
validate(self.owner_thread);
unsafe { DomRoot::from_ref(&*(self.refcount.0 as *const T)) }
}
}
impl<T: DomObject> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
Trusted {
refcount: self.refcount.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
pub(crate) struct LiveDOMReferences {
reflectable_table: RefCell<FxHashMap<*const libc::c_void, Weak<TrustedReference>>>,
promise_table: RefCell<FxHashMap<*const Promise, Vec<Rc<Promise>>>>,
}
impl LiveDOMReferences {
pub(crate) fn destruct() {
LIVE_REFERENCES.with(|r| {
let live_references = r.borrow_mut();
let _ = live_references.promise_table.take();
let _ = live_references.reflectable_table.take();
});
}
fn addref_promise(&self, promise: Rc<Promise>) {
let mut table = self.promise_table.borrow_mut();
table.entry(&*promise).or_default().push(promise)
}
#[expect(clippy::arc_with_non_send_sync)]
unsafe fn addref(&self, ptr: *const libc::c_void) -> Arc<TrustedReference> {
let mut table = self.reflectable_table.borrow_mut();
let capacity = table.capacity();
let len = table.len();
if (0 < capacity) && (capacity <= len) {
trace!("growing refcounted references by {}", len);
remove_nulls(&mut table);
table.reserve(len);
}
match table.entry(ptr) {
Occupied(mut entry) => match entry.get().upgrade() {
Some(refcount) => refcount,
None => {
let refcount = Arc::new(unsafe { TrustedReference::new(ptr) });
entry.insert(Arc::downgrade(&refcount));
refcount
},
},
Vacant(entry) => {
let refcount = Arc::new(unsafe { TrustedReference::new(ptr) });
entry.insert(Arc::downgrade(&refcount));
refcount
},
}
}
}
fn remove_nulls<K: Eq + Hash + Clone, V>(table: &mut FxHashMap<K, Weak<V>>) {
let to_remove: Vec<K> = table
.iter()
.filter(|&(_, value)| Weak::upgrade(value).is_none())
.map(|(key, _)| key.clone())
.collect();
trace!("removing {} refcounted references", to_remove.len());
for key in to_remove {
table.remove(&key);
}
}
pub(crate) unsafe fn trace_refcounted_objects(tracer: *mut JSTracer) {
trace!("tracing live refcounted references");
LIVE_REFERENCES.with(|r| {
let live_references = &*r.borrow();
{
let mut table = live_references.reflectable_table.borrow_mut();
remove_nulls(&mut table);
for obj in table.keys() {
unsafe {
trace_reflector(tracer, "refcounted", &*(*obj as *const Reflector));
}
}
}
{
let table = live_references.promise_table.borrow_mut();
for promise in table.keys() {
unsafe {
trace_reflector(tracer, "refcounted", (**promise).reflector());
}
}
}
});
}