Browse Source

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

Daniel Romero 8 years ago
parent
commit
37916330b4
3 changed files with 49 additions and 1 deletions
  1. 3 1
      src/lib.rs
  2. 44 0
      src/util/channel.rs
  3. 2 0
      src/util/mod.rs

+ 3 - 1
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;
 

+ 44 - 0
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()
+            }
+        }
+    }
+  }
+}

+ 2 - 0
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};