1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
    Appellation: channel <module>
    Creator: FL03 <jo3mccain@icloud.com>
*/
use async_trait::async_trait;

pub trait Receiver<T> {
    type Error;

    fn recv(&mut self) -> Result<T, Self::Error>;
}

pub trait Sender<T> {
    type Error;

    fn send(&mut self, value: T) -> Result<(), Self::Error>;
}

#[async_trait]
pub trait AsyncReceiver<T> {
    type Error;

    async fn recv(&mut self) -> Result<T, Self::Error>;
}

#[async_trait]
pub trait AsyncSender<T>: Send {
    type Error;

    async fn send(&mut self, value: T) -> Result<(), Self::Error>;
}

#[cfg(feature = "std")]
mod std_sync_impl {
    use super::*;
    use std::sync::mpsc;

    impl<T> Receiver<T> for mpsc::Receiver<T> {
        type Error = mpsc::RecvError;

        fn recv(&mut self) -> Result<T, Self::Error> {
            mpsc::Receiver::recv(self)
        }
    }

    impl<T> Sender<T> for mpsc::Sender<T> {
        type Error = mpsc::SendError<T>;

        fn send(&mut self, value: T) -> Result<(), Self::Error> {
            mpsc::Sender::send(self, value)
        }
    }
}

#[cfg(feature = "tokio")]
mod tokio_impl {
    use super::*;
    use tokio::sync::mpsc;

    impl<T> Receiver<T> for mpsc::Receiver<T> {
        type Error = mpsc::error::TryRecvError;

        fn recv(&mut self) -> Result<T, Self::Error> {
            match mpsc::Receiver::blocking_recv(self) {
                Some(v) => Ok(v),
                None => Err(mpsc::error::TryRecvError::Empty),
            }
        }
    }

    macro_rules! impl_async_receiver {

        (@impl $($p:ident)::*.$call:ident -> $err:ty) => {

            #[async_trait::async_trait]
            impl<T> AsyncReceiver<T> for $($p)::*<T>
            where
                T: Send + Sync,
            {
                type Error = $err;

                async fn recv(&mut self) -> Result<T, Self::Error> {
                    $($p)::*::$call(self)
                }
            }
        };
    }

    impl_async_receiver!(@impl mpsc::Receiver.try_recv -> mpsc::error::TryRecvError);
}