From d05cfa7872d6edd0a1b6bd6a9119f7d0e9899660 Mon Sep 17 00:00:00 2001 From: Brad Clawsie Date: Mon, 30 Nov 2026 10:58:44 -0600 Subject: feat: learn_22 commit 70bcd610ff5eaa3684aaea97938344c53d3eb3e1 Author: Brad Clawsie Date: Mon Nov 30 10:53:34 2026 -0600 feat: learn_22 commit b6edc59df72940dd7490febb50c69e0b10e19b54 Author: Brad Clawsie Date: Mon Nov 30 09:36:24 2026 -0600 wip: learn_22 commit fdc8b9e606688cac964822220c8610347b05c644 Author: Brad Clawsie Date: Sun Nov 29 14:46:10 2026 -0600 wip: learn_22 commit 73fa6541d47995adf25a2cbc82f2b2feae69488d Author: Brad Clawsie Date: Sun Nov 29 14:30:29 2026 -0600 wip: learn_22 commit 57398e51bbd90024ebd1f7e6a25ca4432fd2e074 Author: Brad Clawsie Date: Wed Nov 25 15:32:21 2026 -0600 wip: learn_22 --- learn_22/src/event.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 learn_22/src/event.rs (limited to 'learn_22/src/event.rs') diff --git a/learn_22/src/event.rs b/learn_22/src/event.rs new file mode 100644 index 0000000..b9fb3bc --- /dev/null +++ b/learn_22/src/event.rs @@ -0,0 +1,53 @@ +use std::collections::BTreeMap; + +type SubscriptionId = u32; + +type Listener = Box; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Event { + UserCreated { id: u64, name: String }, + UserDeleted { id: u64 }, + MessageReceived { from: u64, text: String }, +} + +pub struct EventBus { + listeners: BTreeMap, + subscription_id: SubscriptionId, +} + +impl EventBus { + pub fn new() -> Self { + Self { + listeners: BTreeMap::new(), + subscription_id: 0, + } + } + + pub fn subscribe(&mut self, callback: F) -> SubscriptionId + where + F: FnMut(&Event) + 'static, + { + let subscription_id = self.subscription_id; + self.listeners.insert(subscription_id, Box::new(callback)); + self.subscription_id += 1; + subscription_id + } + + pub fn unsubscribe(&mut self, id: SubscriptionId) -> bool { + match self.listeners.remove(&id) { + Some(_) => true, + _ => false, + } + } + + pub fn publish(&mut self, event: Event) { + for (_, callback) in &mut self.listeners { + callback(&event); + } + } + + pub fn subscriber_count(&self) -> usize { + self.listeners.len() + } +} -- cgit v1.2.3