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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#![allow(clippy::module_name_repetitions)]

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 as UnboundedSendError, TryRecvError as UnboundedTryRecvError,
    };
    use tokio::sync::mpsc::{UnboundedReceiver as InnerReceiver, UnboundedSender as InnerSender};

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

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

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

    use tokio::sync::Mutex;

    /// An unbounded sender, created with [`unbounded`]
    pub struct UnboundedSender<T>(pub(super) InnerSender<T>);
    /// An unbounded receiver, created with [`unbounded`]
    pub struct UnboundedReceiver<T>(pub(super) Mutex<InnerReceiver<T>>);

    /// An unbounded stream, created with a channel
    pub struct UnboundedStream<T>(pub(super) tokio_stream::wrappers::UnboundedReceiverStream<T>);

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

    /// Create an unbounded channel. This will dynamically allocate whenever the internal buffer is full and a new message is added.
    ///
    /// The names of the [`UnboundedSender`] and [`UnboundedReceiver`] are specifically chosen to be less ergonomic than the [`bounded`] channels. Please consider using a bounded channel instead for performance reasons.
    #[must_use]
    pub fn unbounded<T>() -> (UnboundedSender<T>, UnboundedReceiver<T>) {
        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
        let receiver = Mutex::new(receiver);
        (UnboundedSender(sender), UnboundedReceiver(receiver))
    }
}

/// inner module, used to group feature-specific imports
#[cfg(async_channel_impl = "flume")]
mod inner {
    use flume::{r#async::RecvStream, Receiver, Sender};
    pub use flume::{
        RecvError as UnboundedRecvError, SendError as UnboundedSendError,
        TryRecvError as UnboundedTryRecvError,
    };

    /// An unbounded sender, created with [`unbounded`]
    pub struct UnboundedSender<T>(pub(super) Sender<T>);
    /// An unbounded receiver, created with [`unbounded`]
    pub struct UnboundedReceiver<T>(pub(super) Receiver<T>);
    /// A bounded stream, created with a channel
    pub struct UnboundedStream<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: UnboundedTryRecvError,
    ) -> Option<UnboundedRecvError> {
        match e {
            UnboundedTryRecvError::Empty => None,
            UnboundedTryRecvError::Disconnected => Some(UnboundedRecvError::Disconnected),
        }
    }

    /// Create an unbounded channel. This will dynamically allocate whenever the internal buffer is full and a new message is added.
    ///
    /// The names of the [`UnboundedSender`] and [`UnboundedReceiver`] are specifically chosen to be less ergonomic than the [`bounded`] channels. Please consider using a bounded channel instead for performance reasons.
    #[must_use]
    pub fn unbounded<T>() -> (UnboundedSender<T>, UnboundedReceiver<T>) {
        let (sender, receiver) = flume::unbounded();
        (UnboundedSender(sender), UnboundedReceiver(receiver))
    }
}

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

    /// An unbounded sender, created with [`unbounded`]
    pub struct UnboundedSender<T>(pub(super) Sender<T>);
    /// An unbounded receiver, created with [`unbounded`]
    pub struct UnboundedReceiver<T>(pub(super) Receiver<T>);
    /// An unbounded stream, created with a channel
    pub struct UnboundedStream<T>(pub(super) Receiver<T>);

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

    /// Create an unbounded channel. This will dynamically allocate whenever the internal buffer is full and a new message is added.
    ///
    /// The names of the [`UnboundedSender`] and [`UnboundedReceiver`] are specifically chosen to be less ergonomic than the [`bounded`] channels. Please consider using a bounded channel instead for performance reasons.
    #[must_use]
    pub fn unbounded<T>() -> (UnboundedSender<T>, UnboundedReceiver<T>) {
        let (sender, receiver) = async_std::channel::unbounded();
        (UnboundedSender(sender), UnboundedReceiver(receiver))
    }
}

pub use inner::*;

impl<T> UnboundedSender<T> {
    /// Send a value to the sender half of this channel.
    ///
    /// # Errors
    ///
    /// This may fail if the receiver is dropped.
    #[allow(clippy::unused_async)] // under tokio this function is actually sync
    pub async fn send(&self, msg: T) -> Result<(), UnboundedSendError<T>> {
        #[cfg(async_channel_impl = "flume")]
        let result = self.0.send_async(msg).await;
        #[cfg(async_channel_impl = "tokio")]
        let result = self.0.send(msg);
        #[cfg(not(any(async_channel_impl = "flume", async_channel_impl = "tokio")))]
        let result = self.0.send(msg).await;
        result
    }
}

impl<T> UnboundedReceiver<T> {
    /// Receive a value from the receiver half of this channel.
    ///
    /// Will block until a value is received
    ///
    /// # Errors
    ///
    /// Will produce an error if all senders are dropped
    pub async fn recv(&self) -> Result<T, UnboundedRecvError> {
        #[cfg(async_channel_impl = "flume")]
        let result = self.0.recv_async().await;
        #[cfg(async_channel_impl = "tokio")]
        let result = self.0.lock().await.recv().await.ok_or(UnboundedRecvError);
        #[cfg(not(any(async_channel_impl = "flume", async_channel_impl = "tokio")))]
        let result = self.0.recv().await;
        result
    }
    /// Turn this receiver into a stream.
    pub fn into_stream(self) -> UnboundedStream<T> {
        #[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::UnboundedReceiverStream::new(self.0.into_inner());
        #[cfg(async_channel_impl = "flume")]
        let result = self.0.into_stream();

        UnboundedStream(result)
    }
    /// Try to receive a value from the receiver.
    ///
    /// # Errors
    ///
    /// Will return an error if no value is currently queued. This function will not block.
    pub fn try_recv(&self) -> Result<T, UnboundedTryRecvError> {
        #[cfg(async_channel_impl = "tokio")]
        let result = self
            .0
            .try_lock()
            .map_err(|_| UnboundedTryRecvError::Empty)?
            .try_recv();

        #[cfg(not(async_channel_impl = "tokio"))]
        let result = self.0.try_recv();

        result
    }
    /// 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 there was an error retrieving the first value.
    pub async fn drain_at_least_one(&self) -> Result<Vec<T>, UnboundedRecvError> {
        // 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 all the senders get dropped before this ends.
    pub fn drain(&self) -> Result<Vec<T>, UnboundedRecvError> {
        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)
    }
    /// Attempt to load the length of the messages in queue.
    ///
    /// On some implementations this value does not exist, and this will return `None`.
    #[allow(clippy::len_without_is_empty, clippy::unused_self)]
    #[must_use]
    pub fn len(&self) -> Option<usize> {
        #[cfg(async_channel_impl = "tokio")]
        let result = None;
        #[cfg(not(all(async_channel_impl = "tokio")))]
        let result = Some(self.0.len());
        result
    }
}

impl<T> Stream for UnboundedStream<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::UnboundedReceiverStream<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 UnboundedSender<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

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