use core::ffi::c_void;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use crate::glue;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ContextId(pub u64);
#[derive(Clone, Copy, Debug)]
pub struct Gone {
pub key: usize,
pub id: ContextId,
}
static NEXT: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Copy)]
struct Entry {
id: u64,
mark: usize,
}
fn table() -> &'static Mutex<HashMap<usize, Entry>> {
static T: OnceLock<Mutex<HashMap<usize, Entry>>> = OnceLock::new();
T.get_or_init(|| Mutex::new(HashMap::new()))
}
const ENC_UNDEFINED: u64 = 0xa;
const TAG_NUMBER: u64 = 0xfffe_0000_0000_0000;
fn enc_id(id: u64) -> u64 {
((id as f64).to_bits() as i64).wrapping_add(1i64 << 49) as u64
}
fn dec_number(v: u64) -> Option<f64> {
if (v & TAG_NUMBER) == TAG_NUMBER {
return Some(v as u32 as i32 as f64);
}
if (v & TAG_NUMBER) != 0 {
return Some(f64::from_bits((v as i64).wrapping_sub(1i64 << 49) as u64));
}
None
}
unsafe fn adopt(g: *mut c_void) -> ContextId {
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let name = "redjs#contextId";
let mark = glue::rjs_atom_private(g, name.as_ptr(), name.len());
glue::rjs_define(g, glue::rjs_global(g), mark, enc_id(id), 1 | 2 | 4);
table().lock().unwrap().insert(g as usize, Entry { id, mark: mark as usize });
ContextId(id)
}
unsafe fn mark_matches(g: *mut c_void, e: Entry) -> bool {
let mut out = ENC_UNDEFINED;
if glue::rjs_get(g, glue::rjs_global(g), e.mark as *mut c_void, &mut out) != 0 {
return false;
}
dec_number(out) == Some(e.id as f64)
}
pub unsafe fn register(g: *mut c_void) -> ContextId {
let stale = table().lock().unwrap().remove(&(g as usize));
if let Some(old) = stale {
purge(Gone { key: g as usize, id: ContextId(old.id) });
}
adopt(g)
}
pub unsafe fn ensure(g: *mut c_void) -> ContextId {
let e = table().lock().unwrap().get(&(g as usize)).copied();
match e {
Some(e) if mark_matches(g, e) => ContextId(e.id),
Some(e) => {
table().lock().unwrap().remove(&(g as usize));
purge(Gone { key: g as usize, id: ContextId(e.id) });
adopt(g)
}
None => adopt(g),
}
}
pub fn id_of(g: *mut c_void) -> Option<ContextId> {
table().lock().unwrap().get(&(g as usize)).map(|e| ContextId(e.id))
}
pub fn forget(g: *mut c_void) {
let e = table().lock().unwrap().remove(&(g as usize));
if let Some(e) = e {
purge(Gone { key: g as usize, id: ContextId(e.id) });
}
}
fn purge(gone: Gone) {
crate::errors::forget(gone);
crate::web::forget(gone);
crate::webapi::forget(gone);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::api::Context;
#[test]
fn ids_are_monotonic_and_never_reused() {
let a = Context::new();
let b = Context::new();
let ia = id_of(a.raw()).expect("redjs_context_create registers");
let ib = id_of(b.raw()).expect("redjs_context_create registers");
assert_ne!(ia, ib);
assert!(ia.0 >= 1 && ib.0 >= 1, "0 is never an id");
assert_eq!(unsafe { ensure(a.raw()) }, ia);
assert_eq!(unsafe { ensure(b.raw()) }, ib);
}
#[test]
fn a_recycled_address_starts_from_nothing() {
let c = Context::new();
let g = c.raw();
unsafe {
crate::ffi::redjs_web_install(g);
crate::ffi::redjs_webshim_install(g, core::ptr::null(), 0, core::ptr::null(), 0);
}
let before = id_of(g).unwrap();
assert!(crate::webapi::util::has_state(g), "installed");
assert!(crate::errors::rejection_armed(g));
assert!(crate::web::has_scheduler(g));
let after = unsafe { register(g) };
assert_ne!(after, before, "a newcomer never inherits the old id");
assert!(after.0 > before.0, "ids only grow");
assert!(!crate::webapi::util::has_state(g), "stale WebState must be gone");
assert!(!crate::errors::rejection_armed(g), "stale rejection registration must be gone");
assert!(!crate::web::has_scheduler(g), "stale timers/rAF must be gone");
}
#[test]
fn a_global_without_the_mark_is_a_different_context() {
let c = Context::new();
let g = c.raw();
let first = unsafe { ensure(g) };
let mark = table().lock().unwrap().get(&(g as usize)).unwrap().mark;
unsafe {
let e = Entry { id: first.0, mark };
assert!(mark_matches(g, e));
glue::rjs_define(g, glue::rjs_global(g), mark as *mut c_void, enc_id(first.0 + 1_000_000), 0);
assert!(!mark_matches(g, e));
let second = ensure(g);
assert_ne!(second, first);
assert_eq!(ensure(g), second, "stable once re-marked");
}
}
}