use crate::commands::Command;
pub struct CommandBus {
sender: crossbeam_channel::Sender<Command>,
receiver: crossbeam_channel::Receiver<Command>,
}
#[derive(Clone)]
pub struct CommandSender {
inner: crossbeam_channel::Sender<Command>,
}
pub struct CommandReceiver {
inner: crossbeam_channel::Receiver<Command>,
}
impl CommandBus {
pub fn new() -> Self {
let (sender, receiver) = crossbeam_channel::unbounded();
Self { sender, receiver }
}
pub fn sender(&self) -> CommandSender {
CommandSender { inner: self.sender.clone() }
}
pub fn into_receiver(self) -> CommandReceiver {
CommandReceiver { inner: self.receiver }
}
}
impl Default for CommandBus {
fn default() -> Self {
Self::new()
}
}
impl CommandSender {
pub fn send(&self, command: Command) -> Result<(), crossbeam_channel::SendError<Command>> {
self.inner.send(command)
}
}
impl CommandReceiver {
pub fn try_recv(&self) -> Option<Command> {
self.inner.try_recv().ok()
}
pub fn drain(&self) -> Vec<Command> {
let mut commands = Vec::new();
while let Some(cmd) = self.try_recv() {
commands.push(cmd);
}
commands
}
}