use std::collections::HashMap;
use std::sync::{OnceLock, RwLock};
#[derive(Debug, Clone)]
pub struct Pass {
pub closure_id: u32,
pub args: Vec<u8>,
}
pub type PassResult = Result<Vec<u8>, PassError>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PassError {
UnknownClosureId(u32),
ExecutionError(String),
}
impl std::fmt::Display for PassError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PassError::UnknownClosureId(id) => write!(f, "no handler for closure id {id}"),
PassError::ExecutionError(msg) => write!(f, "handler failed: {msg}"),
}
}
}
impl std::error::Error for PassError {}
pub type PassHandler = Box<dyn Fn(&[u8]) -> PassResult + Send + Sync + 'static>;
fn registry() -> &'static RwLock<HashMap<u32, PassHandler>> {
static CACHE: OnceLock<RwLock<HashMap<u32, PassHandler>>> = OnceLock::new();
CACHE.get_or_init(|| RwLock::new(HashMap::new()))
}
pub fn register<F>(id: u32, handler: F) -> Option<PassHandler>
where
F: Fn(&[u8]) -> PassResult + Send + Sync + 'static,
{
let mut g = registry().write().expect("pass_registry write lock poisoned");
g.insert(id, Box::new(handler))
}
pub fn unregister(id: u32) -> Option<PassHandler> {
let mut g = registry().write().expect("pass_registry write lock poisoned");
g.remove(&id)
}
pub fn is_registered(id: u32) -> bool {
let g = registry().read().expect("pass_registry read lock poisoned");
g.contains_key(&id)
}
pub fn registered_count() -> usize {
let g = registry().read().expect("pass_registry read lock poisoned");
g.len()
}
pub fn execute(pass: &Pass) -> PassResult {
let g = registry().read().expect("pass_registry read lock poisoned");
match g.get(&pass.closure_id) {
Some(handler) => handler(&pass.args),
None => Err(PassError::UnknownClosureId(pass.closure_id)),
}
}
pub fn hash_name(name: &str) -> u32 {
let mut hash: u32 = 0x811C_9DC5;
for byte in name.as_bytes() {
hash ^= *byte as u32;
hash = hash.wrapping_mul(0x0100_0193);
}
hash
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn register_then_execute_round_trips() {
let id = hash_name("flynnel_test_doubler");
register(id, |args| {
assert_eq!(args.len(), 8);
let mut arr = [0u8; 8];
arr.copy_from_slice(args);
let n = u64::from_le_bytes(arr);
Ok((n * 2).to_le_bytes().to_vec())
});
let pass = Pass {
closure_id: id,
args: 21u64.to_le_bytes().to_vec(),
};
let bytes = execute(&pass).expect("execute");
let mut arr = [0u8; 8];
arr.copy_from_slice(&bytes);
assert_eq!(u64::from_le_bytes(arr), 42);
unregister(id);
}
#[test]
fn unknown_id_returns_specific_error() {
let pass = Pass {
closure_id: 0xDEAD_BEEF,
args: vec![],
};
match execute(&pass) {
Err(PassError::UnknownClosureId(id)) => assert_eq!(id, 0xDEAD_BEEF),
other => panic!("expected UnknownClosureId, got {other:?}"),
}
}
#[test]
fn hash_name_is_deterministic() {
let a = hash_name("flynnel.kernels.add_one");
let b = hash_name("flynnel.kernels.add_one");
assert_eq!(a, b);
let c = hash_name("flynnel.kernels.add_two");
assert_ne!(a, c, "different names must hash to different ids");
}
#[test]
fn re_register_returns_previous_handler() {
let id = hash_name("flynnel_test_rereg");
assert!(register(id, |_| Ok(vec![1])).is_none());
let prev = register(id, |_| Ok(vec![2]));
assert!(prev.is_some(), "second register must surface previous");
unregister(id);
}
}