Skip to main content

zruntime/
mpmc.rs

1//! An async multi-producer multi-consumer channel in which each message goes to one receiver.
2//!
3//! [`bounded`] and [`unbounded`] create a channel and return its first [`Sender`] and
4//! [`Receiver`]. Both can be cloned. Both can be sent to other threads, and shared with them, if
5//! the message type `T` is [`Send`](std::marker::Send).
6//!
7//! A sender moves each message into the channel, and a receiver moves it out. Messages are never
8//! cloned, so `T` need not be [`Clone`]. Messages are received in the order they were sent. Each
9//! message goes to exactly one receiver.
10//!
11//! A bounded channel holds at most as many messages as its capacity. [`send`](Sender::send) waits
12//! while the channel is full, and [`try_send`](Sender::try_send) fails. An unbounded channel holds
13//! any number of messages, and sending to it never waits.
14//!
15//! A receiver receives through `&self`, so several tasks can share one receiver by reference and
16//! each wait for the next message. A receiver is also a [`Stream`] of messages. The stream ends
17//! when the channel is closed and empty.
18//!
19//! A channel is closed by [`Sender::close`], by [`Receiver::close`], when its last sender is
20//! dropped, and when its last receiver is dropped. Sending to a closed channel fails and returns
21//! the message. Receiving still returns the messages left in the channel, and fails only when none
22//! is left. When the last receiver is dropped, the messages left in the channel are dropped at
23//! once, because nothing can receive them.
24//!
25//! The channel needs no runtime and works under any executor. It can be used from any thread,
26//! inside a task or not. A thread with no task can wait for a message with the `block_on` of any
27//! executor, as the example below does.
28//!
29//! # Example
30//!
31//! Two senders and two receivers on a channel that holds two messages:
32//!
33//! ```
34//! use std::num::NonZeroUsize;
35//!
36//! use futures::executor::block_on;
37//! use zruntime::mpmc::{RecvError, TrySendError, bounded};
38//!
39//! block_on(async {
40//!     let (s1, r1) = bounded(NonZeroUsize::new(2).unwrap());
41//!     let s2 = s1.clone();
42//!     let r2 = r1.clone();
43//!
44//!     // Two messages, from two different senders.
45//!     s1.send("hello").await.unwrap();
46//!     s2.send("world").await.unwrap();
47//!
48//!     // The channel is full, so `try_send` fails. A `send` would wait for room.
49//!     assert_eq!(s1.try_send("again"), Err(TrySendError::Full("again")));
50//!
51//!     // Each message goes to one receiver, oldest first.
52//!     assert_eq!(r1.recv().await, Ok("hello"));
53//!     assert_eq!(r2.recv().await, Ok("world"));
54//!     assert!(r1.try_recv().unwrap_err().is_empty());
55//!
56//!     // Dropping the last sender closes the channel. The receivers see that once there is no
57//!     // message left in it.
58//!     drop(s1);
59//!     drop(s2);
60//!     assert_eq!(r1.recv().await, Err(RecvError));
61//!     assert_eq!(r2.recv().await, Err(RecvError));
62//! });
63//! ```
64//!
65//! # Spreading work over threads
66//!
67//! A runtime of this crate runs its tasks on one thread at a time, so all of its tasks share one
68//! core. To use more cores, run one runtime per thread and spread the work over them with a
69//! channel. Each thread waits for the next job on its own clone of the same receiver. Each job goes
70//! to whichever thread takes it first, so a busy thread leaves new jobs to the others. The results
71//! come back through a second channel.
72//!
73//! ```
74//! # #[cfg(feature = "runtime")]
75//! # {
76//! use std::{num::NonZeroUsize, thread};
77//!
78//! use zruntime::{LocalRuntime, mpmc};
79//!
80//! let (jobs, job_receiver) = mpmc::bounded::<u64>(NonZeroUsize::new(16).unwrap());
81//! let (result_sender, results) = mpmc::unbounded();
82//!
83//! let workers: Vec<_> = (0..4)
84//!     .map(|_| {
85//!         let jobs = job_receiver.clone();
86//!         let results = result_sender.clone();
87//!
88//!         thread::spawn(move || {
89//!             // A runtime that belongs to this thread.
90//!             let runtime = LocalRuntime::new().unwrap();
91//!             runtime.block_on(async {
92//!                 // The loop ends when the channel is closed and empty.
93//!                 while let Ok(n) = jobs.recv().await {
94//!                     let sum: u64 = (1..=n).sum();
95//!                     results.send(sum).await.unwrap();
96//!                 }
97//!             });
98//!         })
99//!     })
100//!     .collect();
101//! // The workers are the only receivers of jobs and senders of results from here on. The loop
102//! // over the results below ends only when every result sender is dropped, including this one.
103//! drop(job_receiver);
104//! drop(result_sender);
105//!
106//! let runtime = LocalRuntime::new().unwrap();
107//! let total = runtime.block_on(async {
108//!     for n in 1..=100 {
109//!         jobs.send(n).await.unwrap();
110//!     }
111//!     // No more jobs. The workers' loops end after they take the last one.
112//!     drop(jobs);
113//!
114//!     // Results arrive in the order the workers finish their jobs. The loop ends when every
115//!     // worker has dropped its sender.
116//!     let mut total = 0;
117//!     while let Ok(sum) = results.recv().await {
118//!         total += sum;
119//!     }
120//!     total
121//! });
122//!
123//! for worker in workers {
124//!     worker.join().unwrap();
125//! }
126//! assert_eq!(total, (1..=100u64).map(|n| n * (n + 1) / 2).sum());
127//! # }
128//! ```
129//!
130//! If jobs mostly wait for I/O, a worker can spawn a task for each job on its runtime. The jobs
131//! then wait at the same time instead of one after the other.
132//!
133//! # Giving up a wait
134//!
135//! It is safe to drop the future returned by [`Sender::send`] or [`Receiver::recv`] before it
136//! completes. A timeout or a `select` can do this. A dropped [`Recv`] has taken no message. A
137//! dropped [`Send`] has sent none, and its message is dropped with it. If a future was woken for a
138//! message or for room and is then dropped, the wake-up passes to the next task waiting, so no
139//! waiting task is left stranded.
140//!
141//! # Difference with `broadcast`
142//!
143//! The [`broadcast`] module has the same two sides, a sender and a receiver. It delivers every
144//! message to every receiver, as a clone, so its messages must be [`Clone`]. This channel delivers
145//! each message to one receiver only, and moves it there. Use `broadcast` when every receiver
146//! must see every message, and this channel when receivers share the work.
147//!
148//! The `broadcast` module requires the `broadcast` feature.
149//!
150//! # Difference with `async-channel`
151//!
152//! This channel is modelled on [`async-channel`]. It differs in these ways:
153//!
154//! * The capacity of [`bounded`] is a [`NonZeroUsize`], so the type rules out a zero capacity.
155//!   `async-channel` panics on `bounded(0)`.
156//! * Dropping the last receiver drops the messages left in the channel. `async-channel` only closes
157//!   the channel, and the messages stay in it until the channel itself is freed.
158//! * There is no blocking API. Instead of `send_blocking` and `recv_blocking`, a thread with no
159//!   task can wait with the `block_on` of an executor.
160//!
161//! # Performance
162//!
163//! Benchmarks compared this channel with [`async-channel`] 2.5.0 and with the [`mpsc`] channel of
164//! tokio 1.53.1. Tokio's channel has only one receiver, so it is left out of the rows with several
165//! receivers. The messages are `u64`s. The machine is a shared x86-64 one with four cores. Each
166//! thread drives its whole part with one `block_on` call of `futures-lite`. Tasks run on a tokio
167//! runtime with four workers.
168//!
169//! In the rows with threads or tasks, each sender sends 10,000 messages, and the row times all of
170//! them. The row marked "a message" times one message. The times are medians. Times on one thread
171//! stayed within 3% from run to run. The others varied by up to 30%. Sending to tokio's unbounded
172//! channel is not a future, so it needs no poll.
173//!
174//! | What is timed                                             | `mpmc` | async-channel |  tokio |
175//! |-----------------------------------------------------------|-------:|--------------:|-------:|
176//! | A send and a receive, one thread, capacity 1              |  55 ns |        112 ns | 100 ns |
177//! | A send and a receive, one thread, unbounded               |  54 ns |        123 ns |  56 ns |
178//! | 1024 `try_send`s then 1024 `try_recv`s, capacity 1024     |  36 µs |         99 µs |  67 µs |
179//! | 1024 `try_send`s then 1024 `try_recv`s, unbounded         |  36 µs |        112 µs |  47 µs |
180//! | 4 sender and 4 receiver threads, capacity 16              |  72 ms |        240 ms |        |
181//! | 4 sender and 4 receiver threads, unbounded                | 9.7 ms |         16 ms |        |
182//! | 4 sender tasks and 1 receiver task, capacity 16           |  12 ms |         33 ms |  13 ms |
183//! | 4 sender and 4 receiver tasks, capacity 16                |  18 ms |         24 ms |        |
184//! | 1 sender task and 1 receiver task, capacity 16, a message | 280 ns |        550 ns | 540 ns |
185//! | 1 sender thread and 1 receiver thread, capacity 16        |  23 ms |         20 ms |  22 ms |
186//! | 1 sender thread and 1 receiver thread, capacity 1024      | 2.3 ms |        1.7 ms | 2.8 ms |
187//! | 4 sender threads and 1 receiver thread, capacity 16       | 470 ms |        500 ms | 460 ms |
188//!
189//! In the last three rows, the channel keeps filling up or running empty, so a thread has to wait
190//! every few messages. Waiting parks the thread, and waking it takes the OS tens of microseconds
191//! on that machine. That wake-up makes up nearly all of the time. So in these rows the channels
192//! differ in how often a thread had to wait, not in the cost of an operation. Between tasks, which
193//! wake cheaply, this channel takes half as long as the other two, as the "a message" row shows.
194//!
195//! [`Stream`]: futures_core::Stream
196//! [`NonZeroUsize`]: std::num::NonZeroUsize
197//! [`broadcast`]: https://docs.rs/zruntime/latest/zruntime/broadcast/index.html
198//! [`async-channel`]: https://crates.io/crates/async-channel
199//! [`mpsc`]: https://docs.rs/tokio/1.53.1/tokio/sync/mpsc/index.html
200
201use std::{
202    any::Any,
203    collections::VecDeque,
204    error, fmt,
205    future::Future,
206    mem,
207    num::NonZeroUsize,
208    panic::{self, AssertUnwindSafe},
209    pin::Pin,
210    sync::{Arc, Mutex, MutexGuard, PoisonError},
211    task::{Context, Poll},
212};
213
214use futures_core::{
215    ready,
216    stream::{FusedStream, Stream},
217};
218
219use crate::{Event, EventListener};
220
221/// Creates a channel that holds at most `cap` messages.
222///
223/// Returns the first sender and receiver. [`send`](Sender::send) waits while the channel is full,
224/// and [`try_send`](Sender::try_send) fails.
225///
226/// The channel allocates room as messages arrive, not `cap` messages up front. A very large
227/// capacity costs nothing until the messages are there.
228///
229/// # Example
230///
231/// ```
232/// use std::num::NonZeroUsize;
233///
234/// use zruntime::mpmc::{TrySendError, bounded};
235///
236/// let (s, r) = bounded(NonZeroUsize::MIN);
237///
238/// s.try_send(1).unwrap();
239/// // The channel holds one message at most.
240/// assert_eq!(s.try_send(2), Err(TrySendError::Full(2)));
241///
242/// assert_eq!(r.try_recv(), Ok(1));
243/// s.try_send(2).unwrap();
244/// ```
245pub fn bounded<T>(cap: NonZeroUsize) -> (Sender<T>, Receiver<T>) {
246    channel(Some(cap))
247}
248
249/// Creates a channel that holds any number of messages.
250///
251/// Returns the first sender and receiver. Sending to the channel never waits for room.
252///
253/// # Example
254///
255/// ```
256/// use zruntime::mpmc::unbounded;
257///
258/// let (s, r) = unbounded();
259///
260/// for i in 0..100 {
261///     s.try_send(i).unwrap();
262/// }
263/// assert_eq!(s.len(), 100);
264/// assert_eq!(r.try_recv(), Ok(0));
265/// ```
266pub fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
267    channel(None)
268}
269
270/// The sending side of a channel.
271///
272/// Senders can be cloned and shared among threads. When the last sender is dropped, the channel is
273/// closed. No more messages can be sent, but the messages in the channel can still be received.
274///
275/// [`Sender::close`] also closes the channel.
276pub struct Sender<T> {
277    channel: Arc<Channel<T>>,
278}
279
280impl<T> Sender<T> {
281    /// Sends `msg` into the channel.
282    ///
283    /// The returned future completes when the message is in the channel. If the channel is full,
284    /// it waits for a receiver to make room. An unbounded channel is never full.
285    ///
286    /// # Errors
287    ///
288    /// Fails with a [`SendError`], which returns the message, if the channel is closed. This
289    /// includes a channel that is closed while the future waits for room.
290    ///
291    /// # Cancel safety
292    ///
293    /// Dropping the future before it completes is safe. Nothing is sent, and the message is
294    /// dropped.
295    ///
296    /// # Example
297    ///
298    /// Sending to a full channel waits until a receive makes room:
299    ///
300    /// ```
301    /// use std::num::NonZeroUsize;
302    ///
303    /// use futures::{executor::block_on, future::join};
304    /// use zruntime::mpmc::bounded;
305    ///
306    /// let (s, r) = bounded(NonZeroUsize::MIN);
307    ///
308    /// block_on(async {
309    ///     s.send(1).await.unwrap();
310    ///
311    ///     let (sent, received) = join(s.send(2), r.recv()).await;
312    ///     assert_eq!(sent, Ok(()));
313    ///     assert_eq!(received, Ok(1));
314    ///
315    ///     assert_eq!(r.recv().await, Ok(2));
316    /// });
317    /// ```
318    pub fn send(&self, msg: T) -> Send<'_, T> {
319        Send {
320            sender: self,
321            listener: None,
322            msg: Some(msg),
323        }
324    }
325
326    /// Tries to send `msg` into the channel without waiting.
327    ///
328    /// # Errors
329    ///
330    /// Fails with [`TrySendError::Full`] if the channel is full. Fails with
331    /// [`TrySendError::Closed`] if the channel is closed, even if it has room. Both errors return
332    /// the message.
333    ///
334    /// # Example
335    ///
336    /// ```
337    /// use std::num::NonZeroUsize;
338    ///
339    /// use zruntime::mpmc::{TrySendError, bounded};
340    ///
341    /// let (s, r) = bounded(NonZeroUsize::MIN);
342    ///
343    /// assert_eq!(s.try_send(1), Ok(()));
344    /// assert_eq!(s.try_send(2), Err(TrySendError::Full(2)));
345    ///
346    /// drop(r);
347    /// assert_eq!(s.try_send(3), Err(TrySendError::Closed(3)));
348    /// ```
349    pub fn try_send(&self, msg: T) -> Result<(), TrySendError<T>> {
350        self.channel.try_send(msg)
351    }
352
353    /// Closes the channel.
354    ///
355    /// Returns `true` if this call closed the channel, and `false` if it was already closed.
356    ///
357    /// Closing makes every send fail, including sends that are waiting for room. The messages in
358    /// the channel can still be received. Once none is left, receives fail too, including receives
359    /// that are waiting for a message.
360    ///
361    /// # Example
362    ///
363    /// ```
364    /// use zruntime::mpmc::{TryRecvError, TrySendError, unbounded};
365    ///
366    /// let (s, r) = unbounded();
367    /// s.try_send(1).unwrap();
368    ///
369    /// assert!(s.close());
370    /// assert!(!s.close());
371    /// assert_eq!(s.try_send(2), Err(TrySendError::Closed(2)));
372    ///
373    /// assert_eq!(r.try_recv(), Ok(1));
374    /// assert_eq!(r.try_recv(), Err(TryRecvError::Closed));
375    /// ```
376    pub fn close(&self) -> bool {
377        self.channel.close()
378    }
379
380    /// Whether the channel is closed.
381    ///
382    /// A channel is closed by [`Sender::close`], by [`Receiver::close`], when its last sender is
383    /// dropped, and when its last receiver is dropped. Receivers can still receive the messages
384    /// that a closed channel holds.
385    ///
386    /// # Example
387    ///
388    /// ```
389    /// use zruntime::mpmc::unbounded;
390    ///
391    /// let (s, r) = unbounded::<()>();
392    /// assert!(!s.is_closed());
393    ///
394    /// drop(r);
395    /// assert!(s.is_closed());
396    /// ```
397    pub fn is_closed(&self) -> bool {
398        lock(&self.channel.state).closed
399    }
400
401    /// Whether the channel holds no messages.
402    ///
403    /// # Example
404    ///
405    /// ```
406    /// use zruntime::mpmc::unbounded;
407    ///
408    /// let (s, _r) = unbounded();
409    /// assert!(s.is_empty());
410    ///
411    /// s.try_send(1).unwrap();
412    /// assert!(!s.is_empty());
413    /// ```
414    pub fn is_empty(&self) -> bool {
415        lock(&self.channel.state).queue.is_empty()
416    }
417
418    /// Whether the channel holds as many messages as its capacity.
419    ///
420    /// An unbounded channel is never full.
421    ///
422    /// # Example
423    ///
424    /// ```
425    /// use std::num::NonZeroUsize;
426    ///
427    /// use zruntime::mpmc::{bounded, unbounded};
428    ///
429    /// let (s, _r) = bounded(NonZeroUsize::MIN);
430    /// assert!(!s.is_full());
431    /// s.try_send(1).unwrap();
432    /// assert!(s.is_full());
433    ///
434    /// let (s, _r) = unbounded();
435    /// s.try_send(1).unwrap();
436    /// assert!(!s.is_full());
437    /// ```
438    pub fn is_full(&self) -> bool {
439        lock(&self.channel.state).is_full()
440    }
441
442    /// The number of messages in the channel.
443    ///
444    /// Other threads can send and receive at the same time, so the number can be out of date as
445    /// soon as this returns.
446    ///
447    /// # Example
448    ///
449    /// ```
450    /// use zruntime::mpmc::unbounded;
451    ///
452    /// let (s, r) = unbounded();
453    /// assert_eq!(s.len(), 0);
454    ///
455    /// s.try_send(1).unwrap();
456    /// s.try_send(2).unwrap();
457    /// assert_eq!(s.len(), 2);
458    ///
459    /// r.try_recv().unwrap();
460    /// assert_eq!(s.len(), 1);
461    /// ```
462    pub fn len(&self) -> usize {
463        lock(&self.channel.state).queue.len()
464    }
465
466    /// The maximum number of messages the channel holds, or `None` if it is unbounded.
467    ///
468    /// # Example
469    ///
470    /// ```
471    /// use std::num::NonZeroUsize;
472    ///
473    /// use zruntime::mpmc::{bounded, unbounded};
474    ///
475    /// let (s, _r) = bounded::<()>(NonZeroUsize::new(5).unwrap());
476    /// assert_eq!(s.capacity(), NonZeroUsize::new(5));
477    ///
478    /// let (s, _r) = unbounded::<()>();
479    /// assert_eq!(s.capacity(), None);
480    /// ```
481    pub fn capacity(&self) -> Option<NonZeroUsize> {
482        lock(&self.channel.state).capacity
483    }
484
485    /// The number of senders of the channel.
486    ///
487    /// # Example
488    ///
489    /// ```
490    /// use zruntime::mpmc::unbounded;
491    ///
492    /// let (s1, _r) = unbounded::<()>();
493    /// assert_eq!(s1.sender_count(), 1);
494    ///
495    /// let s2 = s1.clone();
496    /// assert_eq!(s1.sender_count(), 2);
497    ///
498    /// drop(s2);
499    /// assert_eq!(s1.sender_count(), 1);
500    /// ```
501    pub fn sender_count(&self) -> usize {
502        lock(&self.channel.state).senders
503    }
504
505    /// The number of receivers of the channel.
506    ///
507    /// # Example
508    ///
509    /// ```
510    /// use zruntime::mpmc::unbounded;
511    ///
512    /// let (s, r1) = unbounded::<()>();
513    /// assert_eq!(s.receiver_count(), 1);
514    ///
515    /// let r2 = r1.clone();
516    /// assert_eq!(s.receiver_count(), 2);
517    ///
518    /// drop((r1, r2));
519    /// assert_eq!(s.receiver_count(), 0);
520    /// ```
521    pub fn receiver_count(&self) -> usize {
522        lock(&self.channel.state).receivers
523    }
524}
525
526impl<T> Clone for Sender<T> {
527    /// Creates another sender of the same channel.
528    ///
529    /// # Example
530    ///
531    /// ```
532    /// use zruntime::mpmc::{TryRecvError, unbounded};
533    ///
534    /// let (s1, r) = unbounded();
535    /// let s2 = s1.clone();
536    ///
537    /// // The channel stays open while at least one sender exists.
538    /// drop(s1);
539    /// s2.try_send(1).unwrap();
540    /// assert_eq!(r.try_recv(), Ok(1));
541    /// assert_eq!(r.try_recv(), Err(TryRecvError::Empty));
542    ///
543    /// drop(s2);
544    /// assert_eq!(r.try_recv(), Err(TryRecvError::Closed));
545    /// ```
546    fn clone(&self) -> Self {
547        lock(&self.channel.state).senders += 1;
548
549        Sender {
550            channel: self.channel.clone(),
551        }
552    }
553}
554
555impl<T> Drop for Sender<T> {
556    fn drop(&mut self) {
557        let closed = {
558            let mut state = lock(&self.channel.state);
559            state.senders -= 1;
560
561            state.senders == 0 && state.close()
562        };
563
564        if closed {
565            self.channel.notify_closed();
566        }
567    }
568}
569
570impl<T> fmt::Debug for Sender<T> {
571    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
572        self.channel.fmt_end("Sender", f)
573    }
574}
575
576/// The receiving side of a channel.
577///
578/// Receivers can be cloned and shared among threads. [`Receiver::recv`] takes `&self`, so a
579/// receiver can also be shared by reference. Each message goes to one receiver. When the last
580/// receiver is dropped, the channel is closed and the messages left in it are dropped, because
581/// nothing can receive them.
582///
583/// [`Receiver::close`] also closes the channel.
584///
585/// A receiver is also a [`Stream`] of messages and a [`FusedStream`]. The stream ends when the
586/// channel is closed and empty.
587///
588/// # Example
589///
590/// ```
591/// use futures::{executor::block_on, stream::StreamExt};
592/// use zruntime::mpmc::unbounded;
593///
594/// let (s, r) = unbounded();
595/// s.try_send(1).unwrap();
596/// s.try_send(2).unwrap();
597/// drop(s);
598///
599/// assert_eq!(block_on(r.collect::<Vec<_>>()), [1, 2]);
600/// ```
601///
602/// [`Stream`]: futures_core::Stream
603/// [`FusedStream`]: futures_core::stream::FusedStream
604pub struct Receiver<T> {
605    channel: Arc<Channel<T>>,
606    /// What the stream of this receiver waits on, kept from one poll of it to the next. A `recv`
607    /// keeps its own listener in its future, so the two never share one.
608    listener: Option<EventListener>,
609}
610
611impl<T> Receiver<T> {
612    /// Receives the oldest message in the channel.
613    ///
614    /// The returned future completes with the message. If the channel has none, it waits for one
615    /// to be sent.
616    ///
617    /// # Errors
618    ///
619    /// Fails with a [`RecvError`] if the channel is closed and has no message left. A closed
620    /// channel still returns the messages it holds.
621    ///
622    /// # Cancel safety
623    ///
624    /// Dropping the future before it completes is safe. It takes no message from the channel.
625    ///
626    /// # Example
627    ///
628    /// ```
629    /// use futures::executor::block_on;
630    /// use zruntime::mpmc::{RecvError, unbounded};
631    ///
632    /// let (s, r) = unbounded();
633    /// s.try_send(1).unwrap();
634    /// drop(s);
635    ///
636    /// block_on(async {
637    ///     assert_eq!(r.recv().await, Ok(1));
638    ///     // The channel is closed, and there is no message left in it.
639    ///     assert_eq!(r.recv().await, Err(RecvError));
640    /// });
641    /// ```
642    pub fn recv(&self) -> Recv<'_, T> {
643        Recv {
644            receiver: self,
645            listener: None,
646        }
647    }
648
649    /// Tries to receive the oldest message in the channel without waiting.
650    ///
651    /// # Errors
652    ///
653    /// Fails with [`TryRecvError::Empty`] if the channel has no message and is not closed. Fails
654    /// with [`TryRecvError::Closed`] if it has no message and is closed. A closed channel still
655    /// returns the messages left in it.
656    ///
657    /// # Example
658    ///
659    /// ```
660    /// use zruntime::mpmc::{TryRecvError, unbounded};
661    ///
662    /// let (s, r) = unbounded();
663    /// assert_eq!(r.try_recv(), Err(TryRecvError::Empty));
664    ///
665    /// s.try_send(1).unwrap();
666    /// assert_eq!(r.try_recv(), Ok(1));
667    ///
668    /// drop(s);
669    /// assert_eq!(r.try_recv(), Err(TryRecvError::Closed));
670    /// ```
671    pub fn try_recv(&self) -> Result<T, TryRecvError> {
672        self.channel.try_recv()
673    }
674
675    /// Closes the channel.
676    ///
677    /// Returns `true` if this call closed the channel, and `false` if it was already closed.
678    ///
679    /// Closing makes every send fail, including sends that are waiting for room. The messages in
680    /// the channel can still be received. Once none is left, receives fail too, including receives
681    /// that are waiting for a message.
682    ///
683    /// # Example
684    ///
685    /// ```
686    /// use zruntime::mpmc::{TryRecvError, TrySendError, unbounded};
687    ///
688    /// let (s, r) = unbounded();
689    /// s.try_send(1).unwrap();
690    ///
691    /// assert!(r.close());
692    /// assert!(!r.close());
693    /// assert_eq!(s.try_send(2), Err(TrySendError::Closed(2)));
694    ///
695    /// assert_eq!(r.try_recv(), Ok(1));
696    /// assert_eq!(r.try_recv(), Err(TryRecvError::Closed));
697    /// ```
698    pub fn close(&self) -> bool {
699        self.channel.close()
700    }
701
702    /// Whether the channel is closed.
703    ///
704    /// See [`Sender::is_closed`] for what closes a channel.
705    ///
706    /// # Example
707    ///
708    /// ```
709    /// use zruntime::mpmc::unbounded;
710    ///
711    /// let (s, r) = unbounded::<()>();
712    /// assert!(!r.is_closed());
713    ///
714    /// drop(s);
715    /// assert!(r.is_closed());
716    /// ```
717    pub fn is_closed(&self) -> bool {
718        lock(&self.channel.state).closed
719    }
720
721    /// Whether the channel holds no messages.
722    ///
723    /// # Example
724    ///
725    /// ```
726    /// use zruntime::mpmc::unbounded;
727    ///
728    /// let (s, r) = unbounded();
729    /// assert!(r.is_empty());
730    ///
731    /// s.try_send(1).unwrap();
732    /// assert!(!r.is_empty());
733    /// ```
734    pub fn is_empty(&self) -> bool {
735        lock(&self.channel.state).queue.is_empty()
736    }
737
738    /// Whether the channel holds as many messages as its capacity.
739    ///
740    /// An unbounded channel is never full.
741    ///
742    /// # Example
743    ///
744    /// ```
745    /// use std::num::NonZeroUsize;
746    ///
747    /// use zruntime::mpmc::bounded;
748    ///
749    /// let (s, r) = bounded(NonZeroUsize::MIN);
750    /// assert!(!r.is_full());
751    ///
752    /// s.try_send(1).unwrap();
753    /// assert!(r.is_full());
754    /// ```
755    pub fn is_full(&self) -> bool {
756        lock(&self.channel.state).is_full()
757    }
758
759    /// The number of messages in the channel.
760    ///
761    /// Other threads can send and receive at the same time, so the number can be out of date as
762    /// soon as this returns.
763    ///
764    /// # Example
765    ///
766    /// ```
767    /// use zruntime::mpmc::unbounded;
768    ///
769    /// let (s, r) = unbounded();
770    /// s.try_send(1).unwrap();
771    /// s.try_send(2).unwrap();
772    /// assert_eq!(r.len(), 2);
773    ///
774    /// r.try_recv().unwrap();
775    /// assert_eq!(r.len(), 1);
776    /// ```
777    pub fn len(&self) -> usize {
778        lock(&self.channel.state).queue.len()
779    }
780
781    /// The maximum number of messages the channel holds, or `None` if it is unbounded.
782    ///
783    /// # Example
784    ///
785    /// ```
786    /// use std::num::NonZeroUsize;
787    ///
788    /// use zruntime::mpmc::{bounded, unbounded};
789    ///
790    /// let (_s, r) = bounded::<()>(NonZeroUsize::new(5).unwrap());
791    /// assert_eq!(r.capacity(), NonZeroUsize::new(5));
792    ///
793    /// let (_s, r) = unbounded::<()>();
794    /// assert_eq!(r.capacity(), None);
795    /// ```
796    pub fn capacity(&self) -> Option<NonZeroUsize> {
797        lock(&self.channel.state).capacity
798    }
799
800    /// The number of senders of the channel.
801    ///
802    /// # Example
803    ///
804    /// ```
805    /// use zruntime::mpmc::unbounded;
806    ///
807    /// let (s1, r) = unbounded::<()>();
808    /// let s2 = s1.clone();
809    /// assert_eq!(r.sender_count(), 2);
810    ///
811    /// drop((s1, s2));
812    /// assert_eq!(r.sender_count(), 0);
813    /// ```
814    pub fn sender_count(&self) -> usize {
815        lock(&self.channel.state).senders
816    }
817
818    /// The number of receivers of the channel.
819    ///
820    /// # Example
821    ///
822    /// ```
823    /// use zruntime::mpmc::unbounded;
824    ///
825    /// let (_s, r1) = unbounded::<()>();
826    /// assert_eq!(r1.receiver_count(), 1);
827    ///
828    /// let r2 = r1.clone();
829    /// assert_eq!(r1.receiver_count(), 2);
830    ///
831    /// drop(r2);
832    /// assert_eq!(r1.receiver_count(), 1);
833    /// ```
834    pub fn receiver_count(&self) -> usize {
835        lock(&self.channel.state).receivers
836    }
837}
838
839impl<T> Clone for Receiver<T> {
840    /// Creates another receiver of the same channel.
841    ///
842    /// The receivers share the messages in the channel. A message is not copied: it goes to one
843    /// receiver.
844    ///
845    /// # Example
846    ///
847    /// ```
848    /// use zruntime::mpmc::{TryRecvError, unbounded};
849    ///
850    /// let (s, r1) = unbounded();
851    /// let r2 = r1.clone();
852    /// s.try_send(1).unwrap();
853    ///
854    /// // The message goes to whichever receiver asks first, and to no other.
855    /// assert_eq!(r2.try_recv(), Ok(1));
856    /// assert_eq!(r1.try_recv(), Err(TryRecvError::Empty));
857    /// ```
858    fn clone(&self) -> Self {
859        lock(&self.channel.state).receivers += 1;
860
861        Receiver {
862            channel: self.channel.clone(),
863            listener: None,
864        }
865    }
866}
867
868impl<T> Drop for Receiver<T> {
869    fn drop(&mut self) {
870        // The receiver is counted out, and the channel closed if it was the last, before any of
871        // somebody else's code runs below: the waker the stream's listener holds, the wakers of
872        // the operations waiting, and the `Drop` of the messages left. Each may panic, and none is
873        // to leave the channel counting a receiver that is gone.
874        let (closed, left) = {
875            let mut state = lock(&self.channel.state);
876            state.receivers -= 1;
877            if state.receivers > 0 {
878                (false, VecDeque::new())
879            } else {
880                // Nothing can receive the messages any more, and no sender can make a receiver.
881                (state.close(), mem::take(&mut state.queue))
882            }
883        };
884
885        let listener = self.listener.take();
886        run_both(
887            // Let go of the stream's listener first: closing the channel would notify it, and
888            // wake the task that last polled the stream, for a receiver that is gone.
889            || drop(listener),
890            || {
891                run_both(
892                    || {
893                        if closed {
894                            self.channel.notify_closed();
895                        }
896                    },
897                    // The messages left go last, once every operation waiting has been told.
898                    || drop(left),
899                )
900            },
901        );
902    }
903}
904
905impl<T> fmt::Debug for Receiver<T> {
906    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
907        self.channel.fmt_end("Receiver", f)
908    }
909}
910
911impl<T> Stream for Receiver<T> {
912    type Item = T;
913
914    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
915        let this = self.get_mut();
916
917        loop {
918            // A listener this stream holds is polled before anything else, as `Recv::poll` does.
919            if let Some(listener) = &mut this.listener {
920                ready!(Pin::new(listener).poll(cx));
921                this.listener = None;
922            }
923
924            loop {
925                match this.channel.try_recv() {
926                    Ok(msg) => {
927                        this.listener = None;
928
929                        return Poll::Ready(Some(msg));
930                    }
931                    Err(TryRecvError::Closed) => {
932                        this.listener = None;
933
934                        return Poll::Ready(None);
935                    }
936                    Err(TryRecvError::Empty) => {}
937                }
938
939                // Nothing to receive yet: listen, then try again, and wait on the listener if that
940                // finds nothing too.
941                match this.listener {
942                    None => this.listener = Some(this.channel.stream_ops.listen_unfenced()),
943                    Some(_) => break,
944                }
945            }
946        }
947    }
948}
949
950impl<T> FusedStream for Receiver<T> {
951    fn is_terminated(&self) -> bool {
952        let state = lock(&self.channel.state);
953
954        state.closed && state.queue.is_empty()
955    }
956}
957
958/// The future returned by [`Sender::send`].
959///
960/// It completes with `Ok(())` when the message is in the channel. If the channel is closed, it
961/// completes with a [`SendError`] that returns the message.
962///
963/// # Panics
964///
965/// Panics if it is polled again after it completed, because the message is gone by then.
966#[must_use = "futures do nothing unless .awaited"]
967pub struct Send<'a, T> {
968    sender: &'a Sender<T>,
969    /// What this future waits on while the channel is full, taken before its last try.
970    listener: Option<EventListener>,
971    /// The message, until it is in the channel or handed back.
972    msg: Option<T>,
973}
974
975// The message is never pinned, so the future is `Unpin` whether the message is or not.
976impl<T> Unpin for Send<'_, T> {}
977
978impl<T> Future for Send<'_, T> {
979    type Output = Result<(), SendError<T>>;
980
981    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
982        let this = self.get_mut();
983
984        loop {
985            // A listener this future holds is polled before anything else. One that completes has
986            // taken its notification. One dropped while notified, as it would be by a try that
987            // succeeds, passes it on to the next operation waiting, which would be woken for
988            // nothing at every ordinary wakeup.
989            if let Some(listener) = &mut this.listener {
990                ready!(Pin::new(listener).poll(cx));
991                this.listener = None;
992            }
993
994            loop {
995                let msg = this
996                    .msg
997                    .take()
998                    .expect("a `Send` is not polled again once it completed: its message is gone");
999
1000                match this.sender.try_send(msg) {
1001                    Ok(()) => {
1002                        // Let go of a listener this future took just now, which may have been
1003                        // notified since: it passes the notification on.
1004                        this.listener = None;
1005
1006                        return Poll::Ready(Ok(()));
1007                    }
1008                    Err(TrySendError::Closed(msg)) => {
1009                        // Let go of a listener, as on success.
1010                        this.listener = None;
1011
1012                        return Poll::Ready(Err(SendError(msg)));
1013                    }
1014                    Err(TrySendError::Full(msg)) => this.msg = Some(msg),
1015                }
1016
1017                // No room yet: listen, then try again, and wait on the listener if that finds none
1018                // either.
1019                match this.listener {
1020                    None => this.listener = Some(this.sender.channel.send_ops.listen_unfenced()),
1021                    Some(_) => break,
1022                }
1023            }
1024        }
1025    }
1026}
1027
1028impl<T> fmt::Debug for Send<'_, T> {
1029    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1030        // The message is left out: `T` need not be `Debug`.
1031        f.debug_struct("Send")
1032            .field("sender", self.sender)
1033            .field("waiting", &self.listener.is_some())
1034            .finish_non_exhaustive()
1035    }
1036}
1037
1038/// The future returned by [`Receiver::recv`].
1039///
1040/// It completes with the message, or with a [`RecvError`] if the channel is closed and has no
1041/// message left.
1042#[must_use = "futures do nothing unless .awaited"]
1043pub struct Recv<'a, T> {
1044    receiver: &'a Receiver<T>,
1045    /// What this future waits on while the channel has no message, taken before its last try.
1046    listener: Option<EventListener>,
1047}
1048
1049impl<T> Future for Recv<'_, T> {
1050    type Output = Result<T, RecvError>;
1051
1052    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1053        let this = self.get_mut();
1054
1055        loop {
1056            // A listener this future holds is polled before anything else, as `Send::poll` does.
1057            if let Some(listener) = &mut this.listener {
1058                ready!(Pin::new(listener).poll(cx));
1059                this.listener = None;
1060            }
1061
1062            loop {
1063                match this.receiver.try_recv() {
1064                    Ok(msg) => {
1065                        // Let go of a listener this future took just now, which may have been
1066                        // notified since: it passes the notification on.
1067                        this.listener = None;
1068
1069                        return Poll::Ready(Ok(msg));
1070                    }
1071                    Err(TryRecvError::Closed) => {
1072                        // Let go of a listener, as on success.
1073                        this.listener = None;
1074
1075                        return Poll::Ready(Err(RecvError));
1076                    }
1077                    Err(TryRecvError::Empty) => {}
1078                }
1079
1080                // Nothing to receive yet: listen, then try again, and wait on the listener if that
1081                // finds nothing too.
1082                match this.listener {
1083                    None => {
1084                        this.listener = Some(this.receiver.channel.recv_ops.listen_unfenced());
1085                    }
1086                    Some(_) => break,
1087                }
1088            }
1089        }
1090    }
1091}
1092
1093impl<T> fmt::Debug for Recv<'_, T> {
1094    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1095        f.debug_struct("Recv")
1096            .field("receiver", self.receiver)
1097            .field("waiting", &self.listener.is_some())
1098            .finish_non_exhaustive()
1099    }
1100}
1101
1102/// The error returned by a [`Sender::send`] that failed because the channel is closed.
1103///
1104/// It holds the message that was not sent.
1105#[derive(PartialEq, Eq, Clone, Copy)]
1106pub struct SendError<T>(pub T);
1107
1108impl<T> SendError<T> {
1109    /// The message that was not sent.
1110    pub fn into_inner(self) -> T {
1111        self.0
1112    }
1113}
1114
1115impl<T> error::Error for SendError<T> {}
1116
1117impl<T> fmt::Debug for SendError<T> {
1118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1119        f.write_str("SendError(..)")
1120    }
1121}
1122
1123impl<T> fmt::Display for SendError<T> {
1124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125        f.write_str("the channel is closed")
1126    }
1127}
1128
1129/// The error returned by a [`Sender::try_send`] that failed.
1130///
1131/// It holds the message that was not sent.
1132#[derive(PartialEq, Eq, Clone, Copy)]
1133pub enum TrySendError<T> {
1134    /// The channel is full but not closed.
1135    Full(T),
1136    /// The channel is closed.
1137    Closed(T),
1138}
1139
1140impl<T> TrySendError<T> {
1141    /// The message that was not sent.
1142    pub fn into_inner(self) -> T {
1143        match self {
1144            TrySendError::Full(msg) | TrySendError::Closed(msg) => msg,
1145        }
1146    }
1147
1148    /// Whether the channel is full but not closed.
1149    pub fn is_full(&self) -> bool {
1150        matches!(self, TrySendError::Full(_))
1151    }
1152
1153    /// Whether the channel is closed.
1154    pub fn is_closed(&self) -> bool {
1155        matches!(self, TrySendError::Closed(_))
1156    }
1157}
1158
1159impl<T> error::Error for TrySendError<T> {}
1160
1161impl<T> fmt::Debug for TrySendError<T> {
1162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1163        match self {
1164            TrySendError::Full(_) => f.write_str("Full(..)"),
1165            TrySendError::Closed(_) => f.write_str("Closed(..)"),
1166        }
1167    }
1168}
1169
1170impl<T> fmt::Display for TrySendError<T> {
1171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1172        match self {
1173            TrySendError::Full(_) => f.write_str("the channel is full"),
1174            TrySendError::Closed(_) => f.write_str("the channel is closed"),
1175        }
1176    }
1177}
1178
1179/// The error returned by a [`Receiver::recv`] that failed.
1180///
1181/// The channel is closed and has no message left.
1182#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1183pub struct RecvError;
1184
1185impl error::Error for RecvError {}
1186
1187impl fmt::Display for RecvError {
1188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1189        f.write_str("the channel is closed and has no message left")
1190    }
1191}
1192
1193/// The error returned by a [`Receiver::try_recv`] that failed.
1194#[derive(PartialEq, Eq, Clone, Copy, Debug)]
1195pub enum TryRecvError {
1196    /// The channel has no message but is not closed.
1197    Empty,
1198    /// The channel is closed and has no message left.
1199    Closed,
1200}
1201
1202impl TryRecvError {
1203    /// Whether the channel has no message but is not closed.
1204    pub fn is_empty(&self) -> bool {
1205        matches!(self, TryRecvError::Empty)
1206    }
1207
1208    /// Whether the channel is closed and has no message left.
1209    pub fn is_closed(&self) -> bool {
1210        matches!(self, TryRecvError::Closed)
1211    }
1212}
1213
1214impl error::Error for TryRecvError {}
1215
1216impl fmt::Display for TryRecvError {
1217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1218        match self {
1219            TryRecvError::Empty => f.write_str("the channel has no message"),
1220            TryRecvError::Closed => f.write_str("the channel is closed and has no message left"),
1221        }
1222    }
1223}
1224
1225/// Makes a channel with room for `capacity` messages, or for any number if it is `None`, and its
1226/// first sender and receiver.
1227fn channel<T>(capacity: Option<NonZeroUsize>) -> (Sender<T>, Receiver<T>) {
1228    let channel = Arc::new(Channel {
1229        state: Mutex::new(State {
1230            // Empty and unallocated, whatever the capacity. It says how many messages the queue may
1231            // hold, not how much room to get for them up front, which would fail for a capacity
1232            // as large as `NonZeroUsize::MAX`.
1233            queue: VecDeque::new(),
1234            capacity,
1235            senders: 1,
1236            receivers: 1,
1237            closed: false,
1238        }),
1239        send_ops: Event::new(),
1240        recv_ops: Event::new(),
1241        stream_ops: Event::new(),
1242    });
1243
1244    let sender = Sender {
1245        channel: channel.clone(),
1246    };
1247    let receiver = Receiver {
1248        channel,
1249        listener: None,
1250    };
1251
1252    (sender, receiver)
1253}
1254
1255/// What the ends of a channel share: its state, behind a lock, and the three events that tell the
1256/// operations waiting on it that the state changed.
1257///
1258/// The events sit beside the lock and not behind it, because an operation notifies them only once
1259/// it has let go of the lock. A notification wakes tasks, and waking one runs its waker, which is
1260/// somebody else's code: it may panic, and it may come straight back to the channel. Run under the
1261/// lock, a waker that panics would leave the operation half done, with the poison-tolerant [`lock`]
1262/// hiding it, and a waker that came back would deadlock. So each operation locks, changes the
1263/// state and decides what to notify, lets go of the lock, notifies, and only then drops any message
1264/// that left the channel, which is somebody else's code too.
1265///
1266/// A panic in any of that leaves the rest of it done. The state is settled before the lock is let
1267/// go of, so a sender or receiver dropped is counted out, and the channel closed, whatever panics
1268/// after. And every notification is sent, and every message and listener dropped, even where one
1269/// before it panics, through [`run_both`]: a waker that panics on one event does not leave an
1270/// operation waiting on another for good.
1271///
1272/// Listening takes no lock either. [`Event`] keeps a notification from slipping in between a
1273/// listener being taken and its caller checking what it waits for, as long as whoever notifies has
1274/// changed that before it notifies, which is the order every operation here keeps. And every
1275/// operation that waits listens first and checks after, as [`Event`] asks: it takes a listener,
1276/// tries again, and waits on the listener only if that fails too.
1277///
1278/// The channel listens and notifies without the event's fences, through `Event::listen_unfenced`,
1279/// `Event::notify_unfenced` and `Event::notify_additional_unfenced`. Every operation checks what it
1280/// waits for under this lock, and every one that changes it does so under this lock and notifies
1281/// after: the lock then orders a check after the change, or the listener taken before the check
1282/// ahead of the notification.
1283///
1284/// What a change notifies, and how:
1285///
1286/// * A message sent is one more for a receiver to take. It notifies `recv_ops` with
1287///   `notify_additional(1)`, which reaches one more waiting [`Recv`]. The counting `notify(1)`
1288///   would not do: it reaches nobody where a `Recv` was notified already and has not been polled
1289///   yet, and that `Recv` takes one message at most, so another one would go on waiting with a
1290///   message in the channel. It notifies `stream_ops` as well, in full, for the reason below.
1291/// * A message received from a bounded channel is room for one more message. It notifies `send_ops`
1292///   with `notify_additional(1)`, for the same reason: one more waiting [`Send`], and whether or
1293///   not an earlier one is notified already. An unbounded channel has no sender waiting for room,
1294///   so a receive from it notifies nobody.
1295/// * A channel closed is news for every operation waiting on it, which are all notified, in full,
1296///   on all three events. Only the call that closed it notifies: an operation that listens after
1297///   that finds the channel closed by its check, and does not wait.
1298///
1299/// A receiver's stream waits on `stream_ops`, and not on `recv_ops` as a [`Recv`] does, and every
1300/// send notifies every stream waiting there. A stream keeps its listener in the [`Receiver`], from
1301/// one poll to the next, and so beyond the life of any one `next()` future that polled it. One that
1302/// is notified and then not polled again, because its `next()` lost a `select!` or its task is busy
1303/// elsewhere, keeps that notification until it is. Had it waited on `recv_ops`, the notification
1304/// could be the one a waiting `Recv` needed for the message sent, which would then wait with the
1305/// message in the channel, possibly for good. With the streams on an event of their own, and all of
1306/// them notified by every send, a stream never holds a notification anybody else needs: each one is
1307/// woken for each message, the one that polls first gets it, and the others find the channel empty
1308/// again and wait for the next.
1309///
1310/// A [`Send`] or a [`Recv`] that completes, either way, lets go of its listener before it returns,
1311/// so a future kept after that holds no notification. One dropped before it completes passes on the
1312/// notification its listener holds, as [`Event`] does for a listener dropped while notified, which
1313/// is what a cancelled operation is to do. And one that holds a listener polls it before it tries
1314/// again, and not after: a listener that completes has taken its notification, where one dropped
1315/// as the try succeeds would pass it on to the next operation waiting, for a wakeup it has no use
1316/// for.
1317struct Channel<T> {
1318    state: Mutex<State<T>>,
1319    /// Send operations waiting for room, in a bounded channel.
1320    send_ops: Event,
1321    /// [`Recv`] operations waiting for a message.
1322    recv_ops: Event,
1323    /// Receivers polled as streams, waiting for a message.
1324    stream_ops: Event,
1325}
1326
1327impl<T> Channel<T> {
1328    /// Puts `msg` in the channel if it is open and has room, and tells the receivers waiting for a
1329    /// message if it did. Otherwise hands `msg` back, in the error.
1330    fn try_send(&self, msg: T) -> Result<(), TrySendError<T>> {
1331        {
1332            let mut state = lock(&self.state);
1333            if state.closed {
1334                return Err(TrySendError::Closed(msg));
1335            }
1336            if state.is_full() {
1337                return Err(TrySendError::Full(msg));
1338            }
1339
1340            state.queue.push_back(msg);
1341        }
1342
1343        // Both, even if a waker panics on the first: a stream left unwoken would wait with the
1344        // message in the channel.
1345        run_both(
1346            || {
1347                self.recv_ops.notify_additional_unfenced(1);
1348            },
1349            || {
1350                self.stream_ops.notify_unfenced(usize::MAX);
1351            },
1352        );
1353
1354        Ok(())
1355    }
1356
1357    /// Takes the oldest message out of the channel, if there is one, and tells a sender waiting for
1358    /// room if that made some.
1359    fn try_recv(&self) -> Result<T, TryRecvError> {
1360        let (msg, bounded) = {
1361            let mut state = lock(&self.state);
1362            let Some(msg) = state.queue.pop_front() else {
1363                return Err(if state.closed {
1364                    TryRecvError::Closed
1365                } else {
1366                    TryRecvError::Empty
1367                });
1368            };
1369
1370            (msg, state.capacity.is_some())
1371        };
1372
1373        if bounded {
1374            self.send_ops.notify_additional_unfenced(1);
1375        }
1376
1377        Ok(msg)
1378    }
1379
1380    /// Closes the channel, and tells the operations waiting on it.
1381    ///
1382    /// Returns `true` if this call closed the channel, and `false` if it was closed already.
1383    fn close(&self) -> bool {
1384        let closed = lock(&self.state).close();
1385
1386        if closed {
1387            self.notify_closed();
1388        }
1389
1390        closed
1391    }
1392
1393    /// Notifies every operation waiting on the channel that it is closed, on all three events
1394    /// even if a waker panics on one of them.
1395    fn notify_closed(&self) {
1396        run_both(
1397            || {
1398                self.send_ops.notify_unfenced(usize::MAX);
1399            },
1400            || {
1401                run_both(
1402                    || {
1403                        self.recv_ops.notify_unfenced(usize::MAX);
1404                    },
1405                    || {
1406                        self.stream_ops.notify_unfenced(usize::MAX);
1407                    },
1408                )
1409            },
1410        );
1411    }
1412
1413    /// Writes what an end of the channel, named `end`, says of the channel for its `Debug`.
1414    ///
1415    /// The numbers are copied out under the lock, and written once it is let go of: a `Formatter`
1416    /// is somebody else's code, which may panic, and may come back to the channel.
1417    fn fmt_end(&self, end: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1418        let (len, capacity, senders, receivers, closed) = {
1419            let state = lock(&self.state);
1420
1421            (
1422                state.queue.len(),
1423                state.capacity,
1424                state.senders,
1425                state.receivers,
1426                state.closed,
1427            )
1428        };
1429
1430        f.debug_struct(end)
1431            .field("len", &len)
1432            .field("capacity", &capacity)
1433            .field("senders", &senders)
1434            .field("receivers", &receivers)
1435            .field("closed", &closed)
1436            .finish()
1437    }
1438}
1439
1440/// What a channel's lock keeps.
1441struct State<T> {
1442    /// The messages in the channel, the oldest first.
1443    queue: VecDeque<T>,
1444    /// How many messages the channel holds at most, or `None` for any number.
1445    capacity: Option<NonZeroUsize>,
1446    /// How many [`Sender`]s there are.
1447    senders: usize,
1448    /// How many [`Receiver`]s there are.
1449    receivers: usize,
1450    /// Whether the channel is closed.
1451    closed: bool,
1452}
1453
1454impl<T> State<T> {
1455    /// Whether the channel holds as many messages as it may.
1456    fn is_full(&self) -> bool {
1457        self.capacity
1458            .is_some_and(|capacity| self.queue.len() >= capacity.get())
1459    }
1460
1461    /// Closes the channel, and tells whether this call did, and not an earlier one.
1462    ///
1463    /// The caller that closed it is to notify every waiting operation once it has let go of the
1464    /// lock.
1465    fn close(&mut self) -> bool {
1466        !mem::replace(&mut self.closed, true)
1467    }
1468}
1469
1470/// The value behind a lock, taken whether or not a panic poisoned it.
1471///
1472/// No user code runs under the channel's lock. A message is moved, never cloned, so there is no
1473/// `T::clone` to run. A message that leaves the channel is dropped once the lock is let go of, and
1474/// the wakers of the operations waiting are woken, cloned and dropped by [`Event`], clear of it.
1475/// Not even a `Formatter` is written to under it. What does run is this module's own code and the
1476/// `VecDeque`'s, which can panic only on a capacity that overflows, before it has changed anything.
1477/// So no panic can have left the state half-changed, and a lock that one poisoned is as good as one
1478/// that none did.
1479fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1480    mutex.lock().unwrap_or_else(PoisonError::into_inner)
1481}
1482
1483/// Runs `first`, and then `second`, even where `first` panics.
1484///
1485/// For what the channel runs once it has let go of its lock: the notifications of its events and
1486/// the drops of its messages and listeners. Each runs somebody else's code, a waker or a message's
1487/// `Drop`, and one that panics is not to leave the rest undone, an operation waiting for a
1488/// notification that never comes or a message never dropped. Three steps nest as
1489/// `run_both(a, || run_both(b, c))`.
1490///
1491/// Where `first` panics, `second` runs as that panic unwinds, under `catch_unwind`: a panic of its
1492/// own is caught there, rather than unwinding out of a drop already unwinding, which would abort
1493/// the process, and the first panic goes on to the caller. Where `first` does not panic, `second`
1494/// runs as any call does, and so does a panic of its own. That path costs nothing beyond the two
1495/// calls, which inline: a send makes it on every message.
1496fn run_both<A, B>(first: A, second: B)
1497where
1498    A: FnOnce(),
1499    B: FnOnce(),
1500{
1501    let mut on_unwind = OnUnwind(Some(second));
1502    first();
1503    if let Some(second) = on_unwind.0.take() {
1504        second();
1505    }
1506}
1507
1508/// A step that runs if a panic unwinds past it, unless it was taken out to run before.
1509///
1510/// A panic of the step's own is caught, and its payload disposed of: the first panic is the one
1511/// that goes on to the caller.
1512struct OnUnwind<F>(Option<F>)
1513where
1514    F: FnOnce();
1515
1516impl<F> Drop for OnUnwind<F>
1517where
1518    F: FnOnce(),
1519{
1520    fn drop(&mut self) {
1521        // Still here only as a panic unwinds: [`run_both`] takes it out to run otherwise.
1522        if let Some(step) = self.0.take()
1523            && let Err(panic) = panic::catch_unwind(AssertUnwindSafe(step))
1524        {
1525            dispose(panic);
1526        }
1527    }
1528}
1529
1530/// Drops the payload of a panic that is to go no further, with a panic of its destructor caught.
1531///
1532/// The payload is somebody else's value, and its `Drop` may panic in turn: out of the drop of an
1533/// [`OnUnwind`], as the first panic unwinds, that would abort the process. The payload of such a
1534/// second panic is dropped too, the same way, and only one that panics a third time is leaked, so
1535/// as not to follow a chain of destructors that each panic. The scheduler has a function like this
1536/// one too, but this module does not use it: the runtime may be left out of the build.
1537fn dispose(payload: Box<dyn Any + std::marker::Send>) {
1538    let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(payload))) else {
1539        return;
1540    };
1541    if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(payload))) {
1542        mem::forget(payload);
1543    }
1544}