1use serde::{Deserialize, Serialize};
7use std::collections::{HashSet, VecDeque};
8
9#[derive(Debug, Clone, Default, Serialize, Deserialize)]
10pub struct Murmur {
11 pub subscriptions: HashSet<String>,
12 pub inbox: VecDeque<(String, String)>,
13 pub outbox: VecDeque<(String, String)>,
14}
15
16impl Murmur {
17 pub fn new() -> Self { Self::default() }
18 pub fn subscribe(&mut self, topic: &str) {
19 self.subscriptions.insert(topic.to_string());
20 }
21 pub fn unsubscribe(&mut self, topic: &str) {
22 self.subscriptions.remove(topic);
23 }
24 pub fn gossip(&mut self, topic: &str, message: &str) {
25 self.outbox.push_back((topic.to_string(), message.to_string()));
26 }
27 pub fn receive(&mut self, topic: &str, message: &str) {
28 if self.subscriptions.contains(topic) {
29 self.inbox.push_back((topic.to_string(), message.to_string()));
30 }
31 }
32 pub fn listen(&mut self) -> Vec<(String, String)> {
33 let msgs: Vec<_> = self.inbox.drain(..).collect();
34 msgs
35 }
36 pub fn pending(&self) -> usize { self.outbox.len() }
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42 #[test]
43 fn test_murmur_basic() {
44 let mut m = Murmur::new();
45 m.subscribe("tick");
46 m.gossip("tick", "hello");
47 assert_eq!(m.pending(), 1);
48 m.receive("tick", "world");
49 assert_eq!(m.listen().len(), 1);
50 }
51}