1use crate::commands::Command;
2
3pub struct CommandBus {
9 sender: crossbeam_channel::Sender<Command>,
10 receiver: crossbeam_channel::Receiver<Command>,
11}
12
13#[derive(Clone)]
18pub struct CommandSender {
19 inner: crossbeam_channel::Sender<Command>,
20}
21
22pub struct CommandReceiver {
24 inner: crossbeam_channel::Receiver<Command>,
25}
26
27impl CommandBus {
28 pub fn new() -> Self {
30 let (sender, receiver) = crossbeam_channel::unbounded();
31 Self { sender, receiver }
32 }
33
34 pub fn sender(&self) -> CommandSender {
36 CommandSender { inner: self.sender.clone() }
37 }
38
39 pub fn into_receiver(self) -> CommandReceiver {
41 CommandReceiver { inner: self.receiver }
42 }
43}
44
45impl Default for CommandBus {
46 fn default() -> Self {
47 Self::new()
48 }
49}
50
51impl CommandSender {
52 pub fn send(&self, command: Command) -> Result<(), crossbeam_channel::SendError<Command>> {
54 self.inner.send(command)
55 }
56}
57
58impl CommandReceiver {
59 pub fn try_recv(&self) -> Option<Command> {
61 self.inner.try_recv().ok()
62 }
63
64 pub fn drain(&self) -> Vec<Command> {
66 let mut commands = Vec::new();
67 while let Some(cmd) = self.try_recv() {
68 commands.push(cmd);
69 }
70 commands
71 }
72}