use std::collections::HashMap;
use std::sync::Arc;
use evorule_tcb::JsonValue;
use evorule_reactor::{IoHandler, IoResult, IoType};
pub struct IoDispatcher {
handlers: HashMap<IoType, Arc<dyn IoHandler>>,
}
impl IoDispatcher {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
}
}
pub fn register(&mut self, io_type: IoType, handler: Arc<dyn IoHandler>) {
self.handlers.insert(io_type, handler);
}
pub fn builder() -> IoDispatcherBuilder {
IoDispatcherBuilder::new()
}
pub async fn dispatch(&self, io_type: &IoType, params: &JsonValue) -> IoResult {
match self.handlers.get(io_type) {
Some(handler) => handler.execute(params).await,
None => {
tracing::warn!(
"Unknown IoType: {}, no handler registered",
io_type.as_str()
);
Err(format!(
"no handler registered for IoType: {}",
io_type.as_str()
))
}
}
}
}
impl Default for IoDispatcher {
fn default() -> Self {
Self::new()
}
}
pub struct IoDispatcherBuilder {
handlers: HashMap<IoType, Arc<dyn IoHandler>>,
}
impl IoDispatcherBuilder {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
}
}
pub fn register(mut self, io_type: IoType, handler: Arc<dyn IoHandler>) -> Self {
self.handlers.insert(io_type, handler);
self
}
pub fn build(self) -> IoDispatcher {
IoDispatcher {
handlers: self.handlers,
}
}
}
impl Default for IoDispatcherBuilder {
fn default() -> Self {
Self::new()
}
}