use std::collections::HashMap;
pub struct Message {
pub kind: String,
pub json: String,
}
pub trait MessageHandler {
fn handle(&self, msg: &Message);
}
pub struct Mediator {
storage: HashMap<String, Vec<&'static dyn MessageHandler>>,
}
impl Mediator {
pub fn new() -> Self {
Self {
storage: HashMap::with_capacity(100),
}
}
pub fn add(&mut self, kind: String, handler: &'static dyn MessageHandler) {
let key = kind.clone();
if self.storage.contains_key(&key) {
let handlers = self.storage.get_mut(&key).unwrap();
handlers.push(handler);
} else {
let mut handlers: Vec<&'static dyn MessageHandler> = Vec::new();
handlers.push(handler);
self.storage.insert(key, handlers);
}
}
pub fn invoke(&self, msg: &Message) {
let kind = msg.kind.clone();
if self.storage.contains_key(&kind) {
let handlers = self.storage.get(&kind).unwrap();
for handler in handlers {
handler.handle(msg);
}
}
}
}
use std::collections::HashMap;
use std::sync::RwLock;
pub struct Message {
pub kind: String,
pub json: String,
}
pub type Implementation = fn(&Message) -> ();
struct MessageHandler {
implementation: Implementation,
}
impl MessageHandler {
pub fn new(implementation: Implementation) -> Self {
Self { implementation }
}
pub fn handle(&self, msg: &Message) {
let _ = &(self.implementation)(msg);
}
}
pub struct Mediator {
storage: RwLock<HashMap<String, Vec<Implementation>>>,
}
impl Mediator {
pub fn new() -> Self {
let data = HashMap::with_capacity(100);
let storage = RwLock::new(data);
Self { storage }
}
pub fn add(&mut self, kind: String, handler: Implementation) {
let key = kind.clone();
let mut backing = self.storage.write().unwrap();
let target = &mut *backing;
if target.contains_key(&key) {
let handlers = target.get_mut(&key).unwrap();
handlers.push(handler);
} else {
let mut handlers: Vec<Implementation> = Vec::new();
handlers.push(handler);
target.insert(key, handlers);
}
}
pub fn invoke(&self, msg: &Message) {
let backing = self.storage.read().unwrap();
let target = &*backing;
if !target.contains_key(&msg.kind) {
return;
}
let handlers = target.get(&msg.kind).unwrap();
for handler in handlers {
let wrapper = MessageHandler::new(*handler);
wrapper.handle(msg);
}
}
}