Created
June 24, 2015 20:56
-
-
Save anonymous/9c09b23eb239ddc0b87c to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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
use std::default::Default; | |
use std::sync::mpsc::{Receiver, Sender, channel}; | |
struct Wrap<T>(T); | |
macro_rules! ident_zip_signal { | |
( () ; ( $($id: ident,)* ) ; ( $($idr:ident: $tyr:ty,)* ) ) => { | |
fn signal( &mut self, $($idr : $tyr,)* ) { | |
for f in self.s.iter_mut() { | |
f($($idr),*); | |
} | |
} | |
}; | |
( ($t0:ty, $($ty:ty,)*) ; ($id0:ident, $($id: ident,)*) ; ($($idr:ident: $tyr:ty,)*) ) => { | |
ident_zip_signal!{($($ty,)*) ; ($($id,)*) ; ( $($idr: $tyr,)* $id0: $t0, ) } | |
} | |
} | |
macro_rules! signal_decl { | |
( $name:ident($($t:ty ),*) ) => { | |
struct $name { | |
s: Vec<Box<FnMut($($t),*)>>, | |
} | |
impl $name { | |
fn new() -> $name { | |
Default::default() | |
} | |
ident_zip_signal!{($($t,)*) ; (a, b, c, d, e, f, g, h,); ()} | |
fn connect(&mut self, wf: Wrap<Box<FnMut($($t),*)>>) { | |
let Wrap(f) = wf; | |
self.s.push(f); | |
} | |
} | |
impl Default for $name { | |
fn default() -> Self { | |
$name { | |
s: Vec::new() | |
} | |
} | |
} | |
} | |
} | |
macro_rules! signal { | |
( $sr:ident with |$obj:ident, $($id:ident),*| $bl:expr ) => ( Wrap({ | |
let sender_clone = $sr.sender.clone(); | |
Box::new(move |$($id),*| {sender_clone.send(Box::new(move |$obj| | |
$bl | |
)).unwrap();}) | |
})) | |
} | |
macro_rules! signalreceiver_decl { | |
( $name: ident($t:ty) ) => { | |
struct $name { | |
receiver: Receiver<Box<FnMut(&mut $t)>>, | |
sender: Sender<Box<FnMut(&mut $t)>>, | |
} | |
impl $name { | |
fn new() -> $name { | |
let (sender, receiver) = channel(); | |
$name { | |
sender: sender, | |
receiver: receiver, | |
} | |
} | |
fn run(&mut self, ss: &mut $t) { | |
match self.receiver.try_recv() { | |
Ok(mut handler) => handler(ss), | |
Err(_) => (), | |
} | |
} | |
} | |
} | |
} | |
signal_decl!{SignalXY(isize, usize)} | |
signalreceiver_decl!{SignalReceiver(isize)} | |
fn main() { | |
let mut s: SignalXY = Default::default(); | |
let mut sr: SignalReceiver = SignalReceiver::new(); | |
let mut data: isize = 10; | |
let mosh: isize = 100; | |
s.connect(signal!(sr with |obj, x, y| println!("mosh {}, x {}, y {}, obj {}", mosh, x, y, obj))); | |
s.signal(5, 6); | |
println!("hi {}", mosh); | |
sr.run(&mut data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment