Skip to content

Commit

Permalink
Setup some publish/subscribe pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
milibopp committed Jan 14, 2015
0 parents commit 45e6649
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
/target
/Cargo.lock
5 changes: 5 additions & 0 deletions Cargo.toml
@@ -0,0 +1,5 @@
[package]

name = "rustfrp"
version = "0.0.1"
authors = ["Eduard Bopp <eduard.bopp@aepsil0n.de>"]
1 change: 1 addition & 0 deletions src/lib.rs
@@ -0,0 +1 @@
mod subject;
46 changes: 46 additions & 0 deletions src/subject.rs
@@ -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));
}
}

0 comments on commit 45e6649

Please sign in to comment.