Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Setup some publish/subscribe pattern
- Loading branch information
0 parents
commit 45e6649
Showing
4 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
/target | ||
/Cargo.lock |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
[package] | ||
|
||
name = "rustfrp" | ||
version = "0.0.1" | ||
authors = ["Eduard Bopp <eduard.bopp@aepsil0n.de>"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
mod subject; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
use std::sync::mpsc::{channel, Sender, Receiver}; | ||
|
||
pub struct Subject<A: Send + Clone> { | ||
senders: Vec<Sender<A>>, | ||
} | ||
|
||
impl<A: Send + Clone> Subject<A> { | ||
pub fn new() -> Subject<A> { | ||
Subject { senders: Vec::new() } | ||
} | ||
|
||
pub fn listen(&mut self) -> Receiver<A> { | ||
let (tx, rx) = channel::<A>(); | ||
self.senders.push(tx); | ||
rx | ||
} | ||
|
||
pub fn send(&mut self, a: A) { | ||
let mut idx_to_remove = vec!(); | ||
for (k, tx) in self.senders.iter().enumerate() { | ||
match tx.send(a.clone()) { | ||
Ok(_) => (), | ||
Err(_) => idx_to_remove.push(k), | ||
} | ||
} | ||
for k in idx_to_remove.into_iter() { | ||
self.senders.remove(k); | ||
} | ||
} | ||
} | ||
|
||
|
||
#[cfg(test)] | ||
mod test { | ||
use super::*; | ||
|
||
#[test] | ||
fn two_receivers() { | ||
let mut sub = Subject::new(); | ||
let r1 = sub.listen(); | ||
let r2 = sub.listen(); | ||
sub.send(3); | ||
assert_eq!(r1.recv(), Ok(3)); | ||
assert_eq!(r2.recv(), Ok(3)); | ||
} | ||
} |