From 37916330b41443b64e34c606c73eb975f3ee9e90 Mon Sep 17 00:00:00 2001 From: Daniel Romero Date: Tue, 31 Jan 2017 21:37:58 +0100 Subject: [PATCH] Add macro to be able to create wrapped senders to send multiple message types to one channel --- src/lib.rs | 4 +++- src/util/channel.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/util/mod.rs | 2 ++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 src/util/channel.rs diff --git a/src/lib.rs b/src/lib.rs index 59e46547..bdf86147 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/util/channel.rs b/src/util/channel.rs new file mode 100644 index 00000000..982b4c27 --- /dev/null +++ b/src/util/channel.rs @@ -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() + } + } + } + } +} \ No newline at end of file diff --git a/src/util/mod.rs b/src/util/mod.rs index 0683f6a0..f550f526 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -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};