use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use crate::{Error, Result};
use super::endpoint::{MemoryInputInner, MemoryOutputInner};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct EventCode(u32);
impl EventCode {
pub(crate) const fn from_raw(raw: u32) -> Self {
Self(raw)
}
pub(crate) fn raw(self) -> u32 {
self.0
}
}
enum Endpoint {
Input(Weak<MemoryInputInner>),
Output(Weak<MemoryOutputInner>),
}
pub(crate) enum RegisteredEndpoint {
Input(Arc<MemoryInputInner>),
Output(Arc<MemoryOutputInner>),
}
struct RegistryState {
next: u32,
endpoints: HashMap<EventCode, Endpoint>,
}
struct Registry {
state: Mutex<RegistryState>,
}
fn registry() -> &'static Registry {
static REGISTRY: OnceLock<Registry> = OnceLock::new();
REGISTRY.get_or_init(|| Registry {
state: Mutex::new(RegistryState {
next: 0x7fff_0000,
endpoints: HashMap::new(),
}),
})
}
pub(crate) fn register_input(endpoint: &Arc<MemoryInputInner>) -> Result<EventCode> {
register(Endpoint::Input(Arc::downgrade(endpoint)))
}
pub(crate) fn register_output(endpoint: &Arc<MemoryOutputInner>) -> Result<EventCode> {
register(Endpoint::Output(Arc::downgrade(endpoint)))
}
fn register(endpoint: Endpoint) -> Result<EventCode> {
let mut state = registry()
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let state = &mut *state;
let (code, next) = vacant_code(state.next, state.endpoints.len(), |raw| {
state.endpoints.contains_key(&EventCode(raw))
})?;
debug_assert_ne!(code.raw(), 0);
state.endpoints.insert(code, endpoint);
state.next = next;
Ok(code)
}
fn vacant_code(
start: u32,
occupied_count: usize,
mut is_occupied: impl FnMut(u32) -> bool,
) -> Result<(EventCode, u32)> {
let mut cursor = start;
for _ in 0..occupied_count.saturating_add(2) {
let code = EventCode(cursor);
cursor = cursor.wrapping_add(1);
if code.raw() == 0 {
continue;
}
if !is_occupied(code.raw()) {
return Ok((code, cursor));
}
}
Err(Error::ResourceExhausted {
resource: "memory endpoint event code",
})
}
pub(crate) fn lookup(code: u32) -> Option<RegisteredEndpoint> {
if code == 0 {
return None;
}
let state = registry()
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match state.endpoints.get(&EventCode(code))? {
Endpoint::Input(endpoint) => endpoint.upgrade().map(RegisteredEndpoint::Input),
Endpoint::Output(endpoint) => endpoint.upgrade().map(RegisteredEndpoint::Output),
}
}
pub(crate) fn unregister(code: EventCode) {
if code.raw() == 0 {
return;
}
registry()
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.endpoints
.remove(&code);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vacant_code_skips_zero_and_continues_after_wraparound() {
let (code, next) = vacant_code(u32::MAX, 1, |raw| raw == u32::MAX).expect("vacant code");
assert_ne!(code.raw(), 0);
assert_eq!(code.raw(), 1);
assert_eq!(next, 2);
}
#[test]
fn vacant_code_skips_occupied_codes() {
let (code, next) = vacant_code(10, 2, |raw| matches!(raw, 10 | 11)).expect("vacant code");
assert_eq!(code.raw(), 12);
assert_eq!(next, 13);
}
#[test]
fn vacant_code_finds_a_code_after_wrapping_past_the_maximum() {
let (code, next) = vacant_code(u32::MAX - 1, 2, |raw| {
matches!(raw, 0xffff_fffe | 0xffff_ffff)
})
.expect("vacant code");
assert_eq!(code.raw(), 1);
assert_eq!(next, 2);
}
#[test]
fn vacant_code_reports_exhaustion_after_the_bounded_candidates() {
assert!(matches!(
vacant_code(3, 1, |_| true),
Err(Error::ResourceExhausted {
resource: "memory endpoint event code"
})
));
}
}