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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use std::pin::Pin;

use futures::Stream;

/// inner module, used to group feature-specific imports
#[cfg(async_channel_impl = "tokio")]
mod inner {
    pub use tokio::sync::mpsc::error::{SendError, TryRecvError};

    use tokio::sync::mpsc::{Receiver as InnerReceiver, Sender as InnerSender};

    /// A receiver error returned from [`Receiver`]'s `recv`
    #[derive(Debug, PartialEq, Eq)]
    pub struct RecvError;

    impl std::fmt::Display for RecvError {
        fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(fmt, stringify!(RecvError))
        }
    }

    impl std::error::Error for RecvError {}

    /// A bounded sender, created with [`bounded`]
    pub struct Sender<T>(pub(super) InnerSender<T>);
    /// A bounded receiver, created with [`bounded`]
    pub struct Receiver<T>(pub(super) InnerReceiver<T>);
    /// A bounded stream, created with a channel
    pub struct BoundedStream<T>(pub(super) tokio_stream::wrappers::ReceiverStream<T>);

    /// Turn a `TryRecvError` into a `RecvError` if it's not `Empty`
    pub(super) fn try_recv_error_to_recv_error(e: TryRecvError) -> Option<RecvError> {
        match e {
            TryRecvError::Empty => None,
            TryRecvError::Disconnected => Some(RecvError),
        }
    }

    /// Create a bounded sender/receiver pair, limited to `len` messages at a time.
    #[must_use]
    pub fn bounded<T>(len: usize) -> (Sender<T>, Receiver<T>) {
        let (sender, receiver) = tokio::sync::mpsc::channel(len);
        (Sender(sender), Receiver(receiver))
    }
}

/// inner module, used to group feature-specific imports
#[cfg(async_channel_impl = "flume")]
mod inner {
    pub use flume::{RecvError, SendError, TryRecvError};

    use flume::{r#async::RecvStream, Receiver as InnerReceiver, Sender as InnerSender};

    /// A bounded sender, created with [`bounded`]
    pub struct Sender<T>(pub(super) InnerSender<T>);
    /// A bounded receiver, created with [`bounded`]
    pub struct Receiver<T>(pub(super) InnerReceiver<T>);
    /// A bounded stream, created with a channel
    pub struct BoundedStream<T: 'static>(pub(super) RecvStream<'static, T>);

    /// Turn a `TryRecvError` into a `RecvError` if it's not `Empty`
    pub(super) fn try_recv_error_to_recv_error(e: TryRecvError) -> Option<RecvError> {
        match e {
            TryRecvError::Empty => None,
            TryRecvError::Disconnected => Some(RecvError::Disconnected),
        }
    }

    /// Create a bounded sender/receiver pair, limited to `len` messages at a time.
    #[must_use]
    pub fn bounded<T>(len: usize) -> (Sender<T>, Receiver<T>) {
        let (sender, receiver) = flume::bounded(len);
        (Sender(sender), Receiver(receiver))
    }
}

/// inner module, used to group feature-specific imports
#[cfg(not(any(async_channel_impl = "flume", async_channel_impl = "tokio")))]
mod inner {
    pub use async_std::channel::{RecvError, SendError, TryRecvError};

    use async_std::channel::{Receiver as InnerReceiver, Sender as InnerSender};

    /// A bounded sender, created with [`channel`]
    pub struct Sender<T>(pub(super) InnerSender<T>);
    /// A bounded receiver, created with [`channel`]
    pub struct Receiver<T>(pub(super) InnerReceiver<T>);
    /// A bounded stream, created with a channel
    pub struct BoundedStream<T>(pub(super) InnerReceiver<T>);

    /// Turn a `TryRecvError` into a `RecvError` if it's not `Empty`
    pub(super) fn try_recv_error_to_recv_error(e: TryRecvError) -> Option<RecvError> {
        match e {
            TryRecvError::Empty => None,
            TryRecvError::Closed => Some(RecvError),
        }
    }

    /// Create a bounded sender/receiver pair, limited to `len` messages at a time.
    #[must_use]
    pub fn bounded<T>(len: usize) -> (Sender<T>, Receiver<T>) {
        let (sender, receiver) = async_std::channel::bounded(len);

        (Sender(sender), Receiver(receiver))
    }
}

pub use inner::*;

impl<T> Sender<T> {
    /// Send a value to the channel. May return a [`SendError`] if the receiver is dropped
    ///
    /// # Errors
    ///
    /// Will return an error if the receiver is dropped
    pub async fn send(&self, msg: T) -> Result<(), SendError<T>> {
        #[cfg(async_channel_impl = "flume")]
        let result = self.0.send_async(msg).await;
        #[cfg(not(all(async_channel_impl = "flume")))]
        let result = self.0.send(msg).await;

        result
    }
}

impl<T> Receiver<T> {
    /// Receive a value from te channel. This will async block until a value is received, or until a [`RecvError`] is encountered.
    ///
    /// # Errors
    ///
    /// Will return an error if the sender is dropped
    pub async fn recv(&mut self) -> Result<T, RecvError> {
        #[cfg(async_channel_impl = "flume")]
        let result = self.0.recv_async().await;
        #[cfg(async_channel_impl = "tokio")]
        let result = self.0.recv().await.ok_or(RecvError);
        #[cfg(not(any(async_channel_impl = "flume", async_channel_impl = "tokio")))]
        let result = self.0.recv().await;

        result
    }
    /// Turn this recever into a stream. This may fail on some implementations if multiple references of a receiver exist
    pub fn into_stream(self) -> BoundedStream<T>
    where
        T: 'static,
    {
        #[cfg(not(any(async_channel_impl = "flume", async_channel_impl = "tokio")))]
        let result = self.0;
        #[cfg(async_channel_impl = "tokio")]
        let result = tokio_stream::wrappers::ReceiverStream::new(self.0);
        #[cfg(async_channel_impl = "flume")]
        let result = self.0.into_stream();

        BoundedStream(result)
    }
    /// Try to receive a channel from the receiver. Will return immediately if there is no value available.
    ///
    /// # Errors
    ///
    /// Will return an error if the sender is dropped
    pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
        self.0.try_recv()
    }
    /// Asynchronously wait for at least 1 value to show up, then will greedily try to receive values until this receiver would block. The resulting values are returned.
    ///
    /// It is guaranteed that the returning vec contains at least 1 value
    ///
    /// # Errors
    ///
    /// Will return an error if the sender is dropped
    pub async fn drain_at_least_one(&mut self) -> Result<Vec<T>, RecvError> {
        // Wait for the first message to come up
        let first = self.recv().await?;
        let mut ret = vec![first];
        loop {
            match self.try_recv() {
                Ok(x) => ret.push(x),
                Err(e) => {
                    if let Some(e) = try_recv_error_to_recv_error(e) {
                        tracing::error!(
                            "Tried to empty {:?} queue but it disconnected while we were emptying it ({} items are being dropped)",
                            std::any::type_name::<Self>(),
                            ret.len()
                        );
                        return Err(e);
                    }
                    break;
                }
            }
        }
        Ok(ret)
    }
    /// Drains the receiver from all messages in the queue, but will not poll for more messages
    ///
    /// # Errors
    ///
    /// Will return an error if the sender is dropped
    pub fn drain(&mut self) -> Result<Vec<T>, RecvError> {
        let mut result = Vec::new();
        loop {
            match self.try_recv() {
                Ok(t) => result.push(t),
                Err(e) => {
                    if let Some(e) = try_recv_error_to_recv_error(e) {
                        return Err(e);
                    }
                    break;
                }
            }
        }
        Ok(result)
    }
}

impl<T> Stream for BoundedStream<T> {
    type Item = T;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        #[cfg(async_channel_impl = "flume")]
        return <flume::r#async::RecvStream<T>>::poll_next(Pin::new(&mut self.0), cx);
        #[cfg(async_channel_impl = "tokio")]
        return <tokio_stream::wrappers::ReceiverStream<T> as Stream>::poll_next(
            Pin::new(&mut self.0),
            cx,
        );
        #[cfg(not(any(async_channel_impl = "flume", async_channel_impl = "tokio")))]
        return <async_std::channel::Receiver<T> as Stream>::poll_next(Pin::new(&mut self.0), cx);
    }
}

// Clone impl
impl<T> Clone for Sender<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

// Debug impl
impl<T> std::fmt::Debug for Sender<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sender").finish()
    }
}
impl<T> std::fmt::Debug for Receiver<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Receiver").finish()
    }
}