Add macro to be able to create wrapped senders to send multiple message types to one channel

This commit is contained in:
Daniel Romero 2017-01-31 21:37:58 +01:00
parent e547a0c3da
commit 37916330b4
3 changed files with 49 additions and 1 deletions

View file

@ -8,6 +8,9 @@
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#[macro_use]
pub mod util;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
@ -58,7 +61,6 @@ pub mod link;
pub mod metadata;
pub mod player;
pub mod stream;
pub mod util;
pub mod version;
pub mod mixer;

44
src/util/channel.rs Normal file
View file

@ -0,0 +1,44 @@
macro_rules! implement_sender {
(name => $name:ident,
wrap => $wrap_type:ident,
with => $with_type:ident,
variant => $variant:ident) => {
pub struct $name {
wrapped_sender: ::std::sync::mpsc::Sender<$with_type>,
}
impl $name {
pub fn create(sender: ::std::sync::mpsc::Sender<$with_type>) -> $name {
$name {
wrapped_sender: sender
}
}
pub fn send(&self, t: $wrap_type) -> Result<(), ::std::sync::mpsc::SendError<$wrap_type>> {
let wrapped = self.wrap(t);
let result = self.wrapped_sender.send(wrapped);
result.map_err(|senderror| {
let ::std::sync::mpsc::SendError(z) = senderror;
::std::sync::mpsc::SendError(self.unwrap(z))
})
}
fn wrap(&self, d: $wrap_type) -> $with_type {
$with_type::$variant(d)
}
fn unwrap(&self, msg: $with_type) -> $wrap_type {
let d = match msg {
$with_type::$variant(d) => d,
_ => unreachable!()
};
d
}
}
impl Clone for $name {
fn clone(&self) -> $name {
$name {
wrapped_sender: self.wrapped_sender.clone()
}
}
}
}
}

View file

@ -11,6 +11,8 @@ mod int128;
mod spotify_id;
mod arcvec;
mod subfile;
#[macro_use]
mod channel;
pub use util::int128::u128;
pub use util::spotify_id::{SpotifyId, FileId};