rustduck-core 1.0.0

Safe typed TSDuck core bindings for rustduck
Documentation
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};

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 Registry {
    next: AtomicU32,
    endpoints: Mutex<HashMap<EventCode, Endpoint>>,
}

fn registry() -> &'static Registry {
    static REGISTRY: OnceLock<Registry> = OnceLock::new();
    REGISTRY.get_or_init(|| Registry {
        next: AtomicU32::new(0x7fff_0000),
        endpoints: Mutex::new(HashMap::new()),
    })
}

pub(crate) fn register_input(endpoint: &Arc<MemoryInputInner>) -> EventCode {
    register(Endpoint::Input(Arc::downgrade(endpoint)))
}

pub(crate) fn register_output(endpoint: &Arc<MemoryOutputInner>) -> EventCode {
    register(Endpoint::Output(Arc::downgrade(endpoint)))
}

fn register(endpoint: Endpoint) -> EventCode {
    loop {
        let code = EventCode(registry().next.fetch_add(1, Ordering::Relaxed));
        if code.0 == 0 {
            continue;
        }
        let mut endpoints = registry()
            .endpoints
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if let std::collections::hash_map::Entry::Vacant(entry) = endpoints.entry(code) {
            entry.insert(endpoint);
            return code;
        }
    }
}

pub(crate) fn lookup(code: u32) -> Option<RegisteredEndpoint> {
    let endpoints = registry()
        .endpoints
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    match 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) {
    registry()
        .endpoints
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .remove(&code);
}