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
/*
    Appellation: specs <module>
    Creator: FL03 <jo3mccain@icloud.com>
*/
use async_trait::async_trait;

#[async_trait]
pub trait AsyncReceiver<T: Send + Sync> {
    type Error;

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

pub trait Receiver<T> {
    type Error;

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

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

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

pub trait Sender<T> {
    type Error;

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

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

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

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

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

#[cfg(feature = "tokio")]
mod tokio_impls {
    use super::{AsyncReceiver, AsyncSender};
    use async_trait::async_trait;

    #[async_trait]
    impl<T: Send + Sync> AsyncReceiver<T> for tokio::sync::mpsc::Receiver<T> {
        type Error = tokio::sync::mpsc::error::TryRecvError;

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

    #[async_trait]
    impl<T: Send + Sync> AsyncSender<T> for tokio::sync::mpsc::Sender<T> {
        type Error = tokio::sync::mpsc::error::SendError<T>;

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

    #[async_trait]
    impl<T: Clone + Send + Sync> AsyncReceiver<T> for tokio::sync::broadcast::Receiver<T> {
        type Error = tokio::sync::broadcast::error::RecvError;

        async fn recv(&mut self) -> Result<T, Self::Error> {
            tokio::sync::broadcast::Receiver::recv(self).await
        }
    }
}