Skip to main content

std/sync/
mpsc.rs

1//! Multi-producer, single-consumer FIFO queue communication primitives.
2//!
3//! This module provides message-based communication over channels, concretely
4//! defined among three types:
5//!
6//! * [`Sender`]
7//! * [`SyncSender`]
8//! * [`Receiver`]
9//!
10//! A [`Sender`] or [`SyncSender`] is used to send data to a [`Receiver`]. Both
11//! senders are clone-able (multi-producer) such that many threads can send
12//! simultaneously to one receiver (single-consumer).
13//!
14//! These channels come in two flavors:
15//!
16//! 1. An asynchronous, infinitely buffered channel. The [`channel`] function
17//!    will return a `(Sender, Receiver)` tuple where all sends will be
18//!    **asynchronous** (they never block for space to become available; see
19//!    [`std::sync`] for precise guarantees on blocking.) The channel
20//!    conceptually has an infinite buffer.
21//!
22//! 2. A synchronous, bounded channel. The [`sync_channel`] function will
23//!    return a `(SyncSender, Receiver)` tuple where the storage for pending
24//!    messages is a pre-allocated buffer of a fixed size. All sends will be
25//!    **synchronous** by blocking until there is buffer space available. Note
26//!    that a bound of 0 is allowed, causing the channel to become a "rendezvous"
27//!    channel where each sender atomically hands off a message to a receiver.
28//!
29//! [`send`]: Sender::send
30//! [`std::sync`]: ../index.html#blocking-guarantees
31//!
32//! ## Disconnection
33//!
34//! The send and receive operations on channels will all return a [`Result`]
35//! indicating whether the operation succeeded or not. An unsuccessful operation
36//! is normally indicative of the other half of a channel having "hung up" by
37//! being dropped in its corresponding thread.
38//!
39//! Once half of a channel has been deallocated, most operations can no longer
40//! continue to make progress, so [`Err`] will be returned. Many applications
41//! will continue to [`unwrap`] the results returned from this module,
42//! instigating a propagation of failure among threads if one unexpectedly dies.
43//!
44//! [`unwrap`]: Result::unwrap
45//!
46//! # Examples
47//!
48//! Simple usage:
49//!
50//! ```
51//! use std::thread;
52//! use std::sync::mpsc::channel;
53//!
54//! // Create a simple streaming channel
55//! let (tx, rx) = channel();
56//! thread::spawn(move || {
57//!     tx.send(10).unwrap();
58//! });
59//! assert_eq!(rx.recv().unwrap(), 10);
60//! ```
61//!
62//! Shared usage:
63//!
64//! ```
65//! use std::thread;
66//! use std::sync::mpsc::channel;
67//!
68//! // Create a shared channel that can be sent along from many threads
69//! // where tx is the sending half (tx for transmission), and rx is the receiving
70//! // half (rx for receiving).
71//! let (tx, rx) = channel();
72//! for i in 0..10 {
73//!     let tx = tx.clone();
74//!     thread::spawn(move || {
75//!         tx.send(i).unwrap();
76//!     });
77//! }
78//!
79//! for _ in 0..10 {
80//!     let j = rx.recv().unwrap();
81//!     assert!(0 <= j && j < 10);
82//! }
83//! ```
84//!
85//! Propagating panics:
86//!
87//! ```
88//! use std::sync::mpsc::channel;
89//!
90//! // The call to recv() will return an error because the channel has already
91//! // hung up (or been deallocated)
92//! let (tx, rx) = channel::<i32>();
93//! drop(tx);
94//! assert!(rx.recv().is_err());
95//! ```
96//!
97//! Synchronous channels:
98//!
99//! ```
100//! use std::thread;
101//! use std::sync::mpsc::sync_channel;
102//!
103//! let (tx, rx) = sync_channel::<i32>(0);
104//! thread::spawn(move || {
105//!     // This will wait for the parent thread to start receiving
106//!     tx.send(53).unwrap();
107//! });
108//! rx.recv().unwrap();
109//! ```
110//!
111//! Unbounded receive loop:
112//!
113//! ```
114//! use std::sync::mpsc::sync_channel;
115//! use std::thread;
116//!
117//! let (tx, rx) = sync_channel(3);
118//!
119//! for _ in 0..3 {
120//!     // It would be the same without thread and clone here
121//!     // since there will still be one `tx` left.
122//!     let tx = tx.clone();
123//!     // cloned tx dropped within thread
124//!     thread::spawn(move || tx.send("ok").unwrap());
125//! }
126//!
127//! // Drop the last sender to stop `rx` waiting for message.
128//! // The program will not complete if we comment this out.
129//! // **All** `tx` needs to be dropped for `rx` to have `Err`.
130//! drop(tx);
131//!
132//! // Unbounded receiver waiting for all senders to complete.
133//! while let Ok(msg) = rx.recv() {
134//!     println!("{msg}");
135//! }
136//!
137//! println!("completed");
138//! ```
139
140#![stable(feature = "rust1", since = "1.0.0")]
141
142// MPSC channels are built as a wrapper around MPMC channels, which
143// were ported from the `crossbeam-channel` crate. MPMC channels are
144// not exposed publicly, but if you are curious about the implementation,
145// that's where everything is.
146
147use core::clone::Share;
148
149use crate::sync::mpmc;
150use crate::time::{Duration, Instant};
151use crate::{error, fmt};
152
153/// The receiving half of Rust's [`channel`] (or [`sync_channel`]) type.
154/// This half can only be owned by one thread.
155///
156/// Messages sent to the channel can be retrieved using [`recv`].
157///
158/// [`recv`]: Receiver::recv
159///
160/// # Examples
161///
162/// ```rust
163/// use std::sync::mpsc::channel;
164/// use std::thread;
165/// use std::time::Duration;
166///
167/// let (send, recv) = channel();
168///
169/// thread::spawn(move || {
170///     send.send("Hello world!").unwrap();
171///     thread::sleep(Duration::from_secs(2)); // block for two seconds
172///     send.send("Delayed for 2 seconds").unwrap();
173/// });
174///
175/// println!("{}", recv.recv().unwrap()); // Received immediately
176/// println!("Waiting...");
177/// println!("{}", recv.recv().unwrap()); // Received after 2 seconds
178/// ```
179#[stable(feature = "rust1", since = "1.0.0")]
180#[cfg_attr(not(test), rustc_diagnostic_item = "MpscReceiver")]
181pub struct Receiver<T> {
182    inner: mpmc::Receiver<T>,
183}
184
185// The receiver port can be sent from place to place, so long as it
186// is not used to receive non-sendable things.
187#[stable(feature = "rust1", since = "1.0.0")]
188unsafe impl<T: Send> Send for Receiver<T> {}
189
190#[stable(feature = "rust1", since = "1.0.0")]
191impl<T> !Sync for Receiver<T> {}
192
193/// An iterator over messages on a [`Receiver`], created by [`iter`].
194///
195/// This iterator will block whenever [`next`] is called,
196/// waiting for a new message, and [`None`] will be returned
197/// when the corresponding channel has hung up.
198///
199/// [`iter`]: Receiver::iter
200/// [`next`]: Iterator::next
201///
202/// # Examples
203///
204/// ```rust
205/// use std::sync::mpsc::channel;
206/// use std::thread;
207///
208/// let (send, recv) = channel();
209///
210/// thread::spawn(move || {
211///     send.send(1u8).unwrap();
212///     send.send(2u8).unwrap();
213///     send.send(3u8).unwrap();
214/// });
215///
216/// for x in recv.iter() {
217///     println!("Got: {x}");
218/// }
219/// ```
220#[stable(feature = "rust1", since = "1.0.0")]
221#[derive(Debug)]
222pub struct Iter<'a, T: 'a> {
223    rx: &'a Receiver<T>,
224}
225
226/// An iterator that attempts to yield all pending values for a [`Receiver`],
227/// created by [`try_iter`].
228///
229/// [`None`] will be returned when there are no pending values remaining or
230/// if the corresponding channel has hung up.
231///
232/// This iterator will never block the caller in order to wait for data to
233/// become available. Instead, it will return [`None`]. (See [`std::sync`] for
234/// precise guarantees on blocking.)
235///
236/// [`try_iter`]: Receiver::try_iter
237/// [`std::sync`]: ../index.html#blocking-guarantees
238///
239/// # Examples
240///
241/// ```rust
242/// use std::sync::mpsc::channel;
243/// use std::thread;
244/// use std::time::Duration;
245///
246/// let (sender, receiver) = channel();
247///
248/// // Nothing is in the buffer yet
249/// assert!(receiver.try_iter().next().is_none());
250/// println!("Nothing in the buffer...");
251///
252/// thread::spawn(move || {
253///     sender.send(1).unwrap();
254///     sender.send(2).unwrap();
255///     sender.send(3).unwrap();
256/// });
257///
258/// println!("Going to sleep...");
259/// thread::sleep(Duration::from_secs(2)); // block for two seconds
260///
261/// for x in receiver.try_iter() {
262///     println!("Got: {x}");
263/// }
264/// ```
265#[stable(feature = "receiver_try_iter", since = "1.15.0")]
266#[derive(Debug)]
267pub struct TryIter<'a, T: 'a> {
268    rx: &'a Receiver<T>,
269}
270
271/// An owning iterator over messages on a [`Receiver`],
272/// created by [`into_iter`].
273///
274/// This iterator will block whenever [`next`]
275/// is called, waiting for a new message, and [`None`] will be
276/// returned if the corresponding channel has hung up.
277///
278/// [`into_iter`]: Receiver::into_iter
279/// [`next`]: Iterator::next
280///
281/// # Examples
282///
283/// ```rust
284/// use std::sync::mpsc::channel;
285/// use std::thread;
286///
287/// let (send, recv) = channel();
288///
289/// thread::spawn(move || {
290///     send.send(1u8).unwrap();
291///     send.send(2u8).unwrap();
292///     send.send(3u8).unwrap();
293/// });
294///
295/// for x in recv.into_iter() {
296///     println!("Got: {x}");
297/// }
298/// ```
299#[stable(feature = "receiver_into_iter", since = "1.1.0")]
300#[derive(Debug)]
301pub struct IntoIter<T> {
302    rx: Receiver<T>,
303}
304
305/// The sending-half of Rust's asynchronous [`channel`] type.
306///
307/// Messages can be sent through this channel with [`send`].
308///
309/// Note: all senders (the original and its clones) need to be dropped for the receiver
310/// to stop blocking to receive messages with [`Receiver::recv`].
311///
312/// [`send`]: Sender::send
313///
314/// # Examples
315///
316/// ```rust
317/// use std::sync::mpsc::channel;
318/// use std::thread;
319///
320/// let (sender, receiver) = channel();
321/// let sender2 = sender.clone();
322///
323/// // First thread owns sender
324/// thread::spawn(move || {
325///     sender.send(1).unwrap();
326/// });
327///
328/// // Second thread owns sender2
329/// thread::spawn(move || {
330///     sender2.send(2).unwrap();
331/// });
332///
333/// let msg = receiver.recv().unwrap();
334/// let msg2 = receiver.recv().unwrap();
335///
336/// assert_eq!(3, msg + msg2);
337/// ```
338#[stable(feature = "rust1", since = "1.0.0")]
339#[cfg_attr(not(test), rustc_diagnostic_item = "MpscSender")]
340pub struct Sender<T> {
341    inner: mpmc::Sender<T>,
342}
343
344// The send port can be sent from place to place, so long as it
345// is not used to send non-sendable things.
346#[stable(feature = "rust1", since = "1.0.0")]
347unsafe impl<T: Send> Send for Sender<T> {}
348
349#[stable(feature = "mpsc_sender_sync", since = "1.72.0")]
350unsafe impl<T: Send> Sync for Sender<T> {}
351
352/// The sending-half of Rust's synchronous [`sync_channel`] type.
353///
354/// Messages can be sent through this channel with [`send`] or [`try_send`].
355///
356/// [`send`] will block if there is no space in the internal buffer.
357///
358/// [`send`]: SyncSender::send
359/// [`try_send`]: SyncSender::try_send
360///
361/// # Examples
362///
363/// ```rust
364/// use std::sync::mpsc::sync_channel;
365/// use std::thread;
366///
367/// // Create a sync_channel with buffer size 2
368/// let (sync_sender, receiver) = sync_channel(2);
369/// let sync_sender2 = sync_sender.clone();
370///
371/// // First thread owns sync_sender
372/// thread::spawn(move || {
373///     sync_sender.send(1).unwrap();
374///     sync_sender.send(2).unwrap();
375/// });
376///
377/// // Second thread owns sync_sender2
378/// thread::spawn(move || {
379///     sync_sender2.send(3).unwrap();
380///     // thread will now block since the buffer is full
381///     println!("Thread unblocked!");
382/// });
383///
384/// let mut msg;
385///
386/// msg = receiver.recv().unwrap();
387/// println!("message {msg} received");
388///
389/// // "Thread unblocked!" will be printed now
390///
391/// msg = receiver.recv().unwrap();
392/// println!("message {msg} received");
393///
394/// msg = receiver.recv().unwrap();
395///
396/// println!("message {msg} received");
397/// ```
398#[stable(feature = "rust1", since = "1.0.0")]
399pub struct SyncSender<T> {
400    inner: mpmc::Sender<T>,
401}
402
403#[stable(feature = "rust1", since = "1.0.0")]
404unsafe impl<T: Send> Send for SyncSender<T> {}
405
406/// An error returned from the [`Sender::send`] or [`SyncSender::send`]
407/// function on **channel**s.
408///
409/// A **send** operation can only fail if the receiving end of a channel is
410/// disconnected, implying that the data could never be received. The error
411/// contains the data being sent as a payload so it can be recovered.
412#[stable(feature = "rust1", since = "1.0.0")]
413#[derive(PartialEq, Eq, Clone, Copy)]
414pub struct SendError<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
415
416/// An error returned from the [`recv`] function on a [`Receiver`].
417///
418/// The [`recv`] operation can only fail if the sending half of a
419/// [`channel`] (or [`sync_channel`]) is disconnected, implying that no further
420/// messages will ever be received.
421///
422/// [`recv`]: Receiver::recv
423#[derive(PartialEq, Eq, Clone, Copy, Debug)]
424#[stable(feature = "rust1", since = "1.0.0")]
425pub struct RecvError;
426
427/// This enumeration is the list of the possible reasons that [`try_recv`] could
428/// not return data when called. This can occur with both a [`channel`] and
429/// a [`sync_channel`].
430///
431/// [`try_recv`]: Receiver::try_recv
432#[derive(PartialEq, Eq, Clone, Copy, Debug)]
433#[stable(feature = "rust1", since = "1.0.0")]
434pub enum TryRecvError {
435    /// This **channel** is currently empty, but the **Sender**(s) have not yet
436    /// disconnected, so data may yet become available.
437    #[stable(feature = "rust1", since = "1.0.0")]
438    Empty,
439
440    /// The **channel**'s sending half has become disconnected, and there will
441    /// never be any more data received on it.
442    #[stable(feature = "rust1", since = "1.0.0")]
443    Disconnected,
444}
445
446/// This enumeration is the list of possible errors that made [`recv_timeout`]
447/// unable to return data when called. This can occur with both a [`channel`] and
448/// a [`sync_channel`].
449///
450/// [`recv_timeout`]: Receiver::recv_timeout
451#[derive(PartialEq, Eq, Clone, Copy, Debug)]
452#[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
453pub enum RecvTimeoutError {
454    /// This **channel** is currently empty, but the **Sender**(s) have not yet
455    /// disconnected, so data may yet become available.
456    #[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
457    Timeout,
458    /// The **channel**'s sending half has become disconnected, and there will
459    /// never be any more data received on it.
460    #[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
461    Disconnected,
462}
463
464/// This enumeration is the list of the possible error outcomes for the
465/// [`try_send`] method.
466///
467/// [`try_send`]: SyncSender::try_send
468#[stable(feature = "rust1", since = "1.0.0")]
469#[derive(PartialEq, Eq, Clone, Copy)]
470pub enum TrySendError<T> {
471    /// The data could not be sent on the [`sync_channel`] because it would require that
472    /// the callee block to send the data.
473    ///
474    /// If this is a buffered channel, then the buffer is full at this time. If
475    /// this is not a buffered channel, then there is no [`Receiver`] available to
476    /// acquire the data.
477    #[stable(feature = "rust1", since = "1.0.0")]
478    Full(#[stable(feature = "rust1", since = "1.0.0")] T),
479
480    /// This [`sync_channel`]'s receiving half has disconnected, so the data could not be
481    /// sent. The data is returned back to the callee in this case.
482    #[stable(feature = "rust1", since = "1.0.0")]
483    Disconnected(#[stable(feature = "rust1", since = "1.0.0")] T),
484}
485
486impl<T> TrySendError<T> {
487    /// Consumes the error and returns the inner value.
488    ///
489    /// # Examples
490    ///
491    /// ```
492    /// #![feature(try_send_error_into_inner)]
493    ///
494    /// use std::sync::mpsc::sync_channel;
495    ///
496    /// let (tx, rx) = sync_channel(0);
497    /// if let Err(err) = tx.try_send("message") {
498    ///     let msg: &'static str = err.into_inner();
499    ///     assert_eq!(msg, "message");
500    /// }
501    /// ```
502    #[unstable(feature = "try_send_error_into_inner", issue = "165102")]
503    pub fn into_inner(self) -> T {
504        match self {
505            TrySendError::Full(inner) | TrySendError::Disconnected(inner) => inner,
506        }
507    }
508}
509
510/// Creates a new asynchronous channel, returning the sender/receiver halves.
511///
512/// All data sent on the [`Sender`] will become available on the [`Receiver`] in
513/// the same order as it was sent, and no [`send`] will block the calling thread
514/// (this channel has an "infinite buffer", unlike [`sync_channel`], which will
515/// block after its buffer limit is reached). [`recv`] will block until a message
516/// is available while there is at least one [`Sender`] alive (including clones).
517///
518/// The [`Sender`] can be cloned to [`send`] to the same channel multiple times, but
519/// only one [`Receiver`] is supported.
520///
521/// If the [`Receiver`] is disconnected while trying to [`send`] with the
522/// [`Sender`], the [`send`] method will return a [`SendError`]. Similarly, if the
523/// [`Sender`] is disconnected while trying to [`recv`], the [`recv`] method will
524/// return a [`RecvError`].
525///
526/// [`send`]: Sender::send
527/// [`recv`]: Receiver::recv
528///
529/// # Examples
530///
531/// ```
532/// use std::sync::mpsc::channel;
533/// use std::thread;
534///
535/// let (sender, receiver) = channel();
536///
537/// // Spawn off an expensive computation
538/// thread::spawn(move || {
539/// #   fn expensive_computation() {}
540///     sender.send(expensive_computation()).unwrap();
541/// });
542///
543/// // Do some useful work for a while
544///
545/// // Let's see what that answer was
546/// println!("{:?}", receiver.recv().unwrap());
547/// ```
548#[must_use]
549#[stable(feature = "rust1", since = "1.0.0")]
550pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
551    let (tx, rx) = mpmc::channel();
552    (Sender { inner: tx }, Receiver { inner: rx })
553}
554
555/// Creates a new synchronous, bounded channel.
556///
557/// All data sent on the [`SyncSender`] will become available on the [`Receiver`]
558/// in the same order as it was sent. Like asynchronous [`channel`]s, the
559/// [`Receiver`] will block until a message becomes available. `sync_channel`
560/// differs greatly in the semantics of the sender, however.
561///
562/// This channel has an internal buffer on which messages will be queued.
563/// `bound` specifies the buffer size. When the internal buffer becomes full,
564/// future sends will *block* waiting for the buffer to open up. Note that a
565/// buffer size of 0 is valid, in which case this becomes "rendezvous channel"
566/// where each [`send`] will not return until a [`recv`] is paired with it.
567///
568/// The [`SyncSender`] can be cloned to [`send`] to the same channel multiple
569/// times, but only one [`Receiver`] is supported.
570///
571/// Like asynchronous channels, if the [`Receiver`] is disconnected while trying
572/// to [`send`] with the [`SyncSender`], the [`send`] method will return a
573/// [`SendError`]. Similarly, If the [`SyncSender`] is disconnected while trying
574/// to [`recv`], the [`recv`] method will return a [`RecvError`].
575///
576/// [`send`]: SyncSender::send
577/// [`recv`]: Receiver::recv
578///
579/// # Examples
580///
581/// ```
582/// use std::sync::mpsc::sync_channel;
583/// use std::thread;
584///
585/// let (sender, receiver) = sync_channel(1);
586///
587/// // this returns immediately
588/// sender.send(1).unwrap();
589///
590/// thread::spawn(move || {
591///     // this will block until the previous message has been received
592///     sender.send(2).unwrap();
593/// });
594///
595/// assert_eq!(receiver.recv().unwrap(), 1);
596/// assert_eq!(receiver.recv().unwrap(), 2);
597/// ```
598#[must_use]
599#[stable(feature = "rust1", since = "1.0.0")]
600pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>) {
601    let (tx, rx) = mpmc::sync_channel(bound);
602    (SyncSender { inner: tx }, Receiver { inner: rx })
603}
604
605////////////////////////////////////////////////////////////////////////////////
606// Sender
607////////////////////////////////////////////////////////////////////////////////
608
609impl<T> Sender<T> {
610    /// Attempts to send a value on this channel, returning it back if it could
611    /// not be sent.
612    ///
613    /// A successful send occurs when it is determined that the other end of
614    /// the channel has not hung up already. An unsuccessful send would be one
615    /// where the corresponding receiver has already been deallocated. Note
616    /// that a return value of [`Err`] means that the data will never be
617    /// received, but a return value of [`Ok`] does *not* mean that the data
618    /// will be received. It is possible for the corresponding receiver to
619    /// hang up immediately after this function returns [`Ok`].
620    ///
621    /// This method will never block the caller in order to wait for space to
622    /// become available. (See [`std::sync`] for precise guarantees on blocking.)
623    ///
624    /// [`std::sync`]: ../index.html#blocking-guarantees
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// use std::sync::mpsc::channel;
630    ///
631    /// let (tx, rx) = channel();
632    ///
633    /// // This send is always successful
634    /// tx.send(1).unwrap();
635    ///
636    /// // This send will fail because the receiver is gone
637    /// drop(rx);
638    /// assert_eq!(tx.send(1).unwrap_err().0, 1);
639    /// ```
640    #[stable(feature = "rust1", since = "1.0.0")]
641    pub fn send(&self, t: T) -> Result<(), SendError<T>> {
642        self.inner.send(t)
643    }
644
645    /// Returns `true` if the channel is disconnected.
646    ///
647    /// Note that a return value of `false` does not guarantee the channel will
648    /// remain connected. The channel may be disconnected immediately after this method
649    /// returns, so a subsequent [`Sender::send`] may still fail with [`SendError`].
650    ///
651    /// # Examples
652    ///
653    /// ```
654    /// #![feature(mpsc_is_disconnected)]
655    ///
656    /// use std::sync::mpsc::channel;
657    ///
658    /// let (tx, rx) = channel::<i32>();
659    /// assert!(!tx.is_disconnected());
660    /// drop(rx);
661    /// assert!(tx.is_disconnected());
662    /// ```
663    #[unstable(feature = "mpsc_is_disconnected", issue = "153668")]
664    pub fn is_disconnected(&self) -> bool {
665        self.inner.is_disconnected()
666    }
667
668    /// Returns `true` if the channel is empty.
669    ///
670    /// Note: Zero-capacity channels are always empty.
671    ///
672    /// # Examples
673    ///
674    /// ```
675    /// #![feature(mpsc_channel_len)]
676    ///
677    /// use std::sync::mpsc;
678    /// use std::thread;
679    ///
680    /// let (send, _recv) = mpsc::channel();
681    ///
682    /// let tx1 = send.clone();
683    /// let tx2 = send.clone();
684    ///
685    /// assert!(tx1.is_empty());
686    ///
687    /// let handle = thread::spawn(move || {
688    ///     tx2.send(1u8).unwrap();
689    /// });
690    ///
691    /// handle.join().unwrap();
692    ///
693    /// assert!(!tx1.is_empty());
694    /// ```
695    #[unstable(feature = "mpsc_channel_len", issue = "165247")]
696    pub fn is_empty(&self) -> bool {
697        self.inner.is_empty()
698    }
699
700    /// Returns the number of messages in the channel.
701    ///
702    /// # Examples
703    ///
704    /// ```
705    /// #![feature(mpsc_channel_len)]
706    ///
707    /// use std::sync::mpsc;
708    /// use std::thread;
709    ///
710    /// let (send, _recv) = mpsc::channel();
711    /// let (tx1, tx2) = (send.clone(), send.clone());
712    ///
713    /// assert_eq!(tx1.len(), 0);
714    ///
715    /// let handle = thread::spawn(move || {
716    ///     tx2.send(1u8).unwrap();
717    /// });
718    ///
719    /// handle.join().unwrap();
720    ///
721    /// assert_eq!(tx1.len(), 1);
722    /// ```
723    #[unstable(feature = "mpsc_channel_len", issue = "165247")]
724    pub fn len(&self) -> usize {
725        self.inner.len()
726    }
727}
728
729#[stable(feature = "rust1", since = "1.0.0")]
730impl<T> Clone for Sender<T> {
731    /// Clone a sender to send to other threads.
732    ///
733    /// Note, be aware of the lifetime of the sender because all senders
734    /// (including the original) need to be dropped in order for
735    /// [`Receiver::recv`] to stop blocking.
736    fn clone(&self) -> Sender<T> {
737        Sender { inner: self.inner.clone() }
738    }
739}
740
741#[unstable(feature = "share_trait", issue = "156756")]
742impl<T> Share for Sender<T> {}
743
744#[stable(feature = "mpsc_debug", since = "1.8.0")]
745impl<T> fmt::Debug for Sender<T> {
746    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
747        f.debug_struct("Sender").finish_non_exhaustive()
748    }
749}
750
751////////////////////////////////////////////////////////////////////////////////
752// SyncSender
753////////////////////////////////////////////////////////////////////////////////
754
755impl<T> SyncSender<T> {
756    /// Sends a value on this synchronous channel.
757    ///
758    /// This function will *block* until space in the internal buffer becomes
759    /// available or a receiver is available to hand off the message to.
760    ///
761    /// Note that a successful send does *not* guarantee that the receiver will
762    /// ever see the data if there is a buffer on this channel. Items may be
763    /// enqueued in the internal buffer for the receiver to receive at a later
764    /// time. If the buffer size is 0, however, the channel becomes a rendezvous
765    /// channel and it guarantees that the receiver has indeed received
766    /// the data if this function returns success.
767    ///
768    /// This function will never panic, but it may return [`Err`] if the
769    /// [`Receiver`] has disconnected and is no longer able to receive
770    /// information.
771    ///
772    /// # Examples
773    ///
774    /// ```rust
775    /// use std::sync::mpsc::sync_channel;
776    /// use std::thread;
777    ///
778    /// // Create a rendezvous sync_channel with buffer size 0
779    /// let (sync_sender, receiver) = sync_channel(0);
780    ///
781    /// thread::spawn(move || {
782    ///    println!("sending message...");
783    ///    sync_sender.send(1).unwrap();
784    ///    // Thread is now blocked until the message is received
785    ///
786    ///    println!("...message received!");
787    /// });
788    ///
789    /// let msg = receiver.recv().unwrap();
790    /// assert_eq!(1, msg);
791    /// ```
792    #[stable(feature = "rust1", since = "1.0.0")]
793    pub fn send(&self, t: T) -> Result<(), SendError<T>> {
794        self.inner.send(t)
795    }
796
797    /// Attempts to send a value on this channel without blocking.
798    ///
799    /// This method differs from [`send`] by returning immediately if the
800    /// channel's buffer is full or no receiver is waiting to acquire some
801    /// data. Compared with [`send`], this function has two failure cases
802    /// instead of one (one for disconnection, one for a full buffer).
803    ///
804    /// See [`send`] for notes about guarantees of whether the
805    /// receiver has received the data or not if this function is successful.
806    ///
807    /// [`send`]: Self::send
808    ///
809    /// # Examples
810    ///
811    /// ```rust
812    /// use std::sync::mpsc::sync_channel;
813    /// use std::thread;
814    ///
815    /// // Create a sync_channel with buffer size 1
816    /// let (sync_sender, receiver) = sync_channel(1);
817    /// let sync_sender2 = sync_sender.clone();
818    ///
819    /// // First thread owns sync_sender
820    /// let handle1 = thread::spawn(move || {
821    ///     sync_sender.send(1).unwrap();
822    ///     sync_sender.send(2).unwrap();
823    ///     // Thread blocked
824    /// });
825    ///
826    /// // Second thread owns sync_sender2
827    /// let handle2 = thread::spawn(move || {
828    ///     // This will return an error and send
829    ///     // no message if the buffer is full
830    ///     let _ = sync_sender2.try_send(3);
831    /// });
832    ///
833    /// let mut msg;
834    /// msg = receiver.recv().unwrap();
835    /// println!("message {msg} received");
836    ///
837    /// msg = receiver.recv().unwrap();
838    /// println!("message {msg} received");
839    ///
840    /// // Third message may have never been sent
841    /// match receiver.try_recv() {
842    ///     Ok(msg) => println!("message {msg} received"),
843    ///     Err(_) => println!("the third message was never sent"),
844    /// }
845    ///
846    /// // Wait for threads to complete
847    /// handle1.join().unwrap();
848    /// handle2.join().unwrap();
849    /// ```
850    #[stable(feature = "rust1", since = "1.0.0")]
851    pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
852        self.inner.try_send(t)
853    }
854
855    // Attempts to send for a value on this receiver, returning an error if the
856    // corresponding channel has hung up, or if it waits more than `timeout`.
857    //
858    // This method is currently only used for tests.
859    #[unstable(issue = "none", feature = "std_internals")]
860    #[doc(hidden)]
861    pub fn send_timeout(&self, t: T, timeout: Duration) -> Result<(), mpmc::SendTimeoutError<T>> {
862        self.inner.send_timeout(t, timeout)
863    }
864
865    /// Returns `true` if the channel is empty.
866    ///
867    /// Note: Zero-capacity channels are always empty.
868    ///
869    /// # Examples
870    ///
871    /// ```
872    /// #![feature(mpsc_channel_len)]
873    ///
874    /// use std::sync::mpsc;
875    /// use std::thread;
876    ///
877    /// let (send, _recv) = mpsc::sync_channel(1);
878    ///
879    /// let tx1 = send.clone();
880    /// let tx2 = send.clone();
881    ///
882    /// assert!(tx1.is_empty());
883    ///
884    /// let handle = thread::spawn(move || {
885    ///     tx2.send(1u8).unwrap();
886    /// });
887    ///
888    /// handle.join().unwrap();
889    ///
890    /// assert!(!tx1.is_empty());
891    /// ```
892    #[unstable(feature = "mpsc_channel_len", issue = "165247")]
893    pub fn is_empty(&self) -> bool {
894        self.inner.is_empty()
895    }
896
897    /// Returns the number of messages in the channel.
898    ///
899    /// # Examples
900    ///
901    /// ```
902    /// #![feature(mpsc_channel_len)]
903    ///
904    /// use std::sync::mpsc;
905    ///
906    /// let (tx, rx) = mpsc::sync_channel(2);
907    ///
908    /// assert_eq!(tx.len(), 0);
909    ///
910    /// tx.send(1u8).unwrap();
911    /// tx.send(2u8).unwrap();
912    ///
913    /// assert_eq!(tx.len(), 2);
914    ///
915    /// rx.recv().unwrap();
916    ///
917    /// assert_eq!(tx.len(), 1);
918    /// ```
919    #[unstable(feature = "mpsc_channel_len", issue = "165247")]
920    pub fn len(&self) -> usize {
921        self.inner.len()
922    }
923}
924
925#[stable(feature = "rust1", since = "1.0.0")]
926impl<T> Clone for SyncSender<T> {
927    fn clone(&self) -> SyncSender<T> {
928        SyncSender { inner: self.inner.clone() }
929    }
930}
931
932#[unstable(feature = "share_trait", issue = "156756")]
933impl<T> Share for SyncSender<T> {}
934
935#[stable(feature = "mpsc_debug", since = "1.8.0")]
936impl<T> fmt::Debug for SyncSender<T> {
937    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938        f.debug_struct("SyncSender").finish_non_exhaustive()
939    }
940}
941
942////////////////////////////////////////////////////////////////////////////////
943// Receiver
944////////////////////////////////////////////////////////////////////////////////
945
946impl<T> Receiver<T> {
947    /// Attempts to return a pending value on this receiver without blocking.
948    ///
949    /// This method will never block the caller in order to wait for data to
950    /// become available. Instead, this will always return immediately with a
951    /// possible option of pending data on the channel. (See [`std::sync`] for
952    /// precise guarantees on blocking.)
953    ///
954    /// This is useful for a flavor of "optimistic check" before deciding to
955    /// block on a receiver.
956    ///
957    /// Compared with [`recv`], this function has two failure cases instead of one
958    /// (one for disconnection, one for an empty buffer).
959    ///
960    /// [`recv`]: Self::recv
961    /// [`std::sync`]: ../index.html#blocking-guarantees
962    ///
963    /// # Examples
964    ///
965    /// ```rust
966    /// use std::sync::mpsc::{Receiver, channel};
967    ///
968    /// let (_, receiver): (_, Receiver<i32>) = channel();
969    ///
970    /// assert!(receiver.try_recv().is_err());
971    /// ```
972    #[stable(feature = "rust1", since = "1.0.0")]
973    pub fn try_recv(&self) -> Result<T, TryRecvError> {
974        self.inner.try_recv()
975    }
976
977    /// Attempts to wait for a value on this receiver, returning an error if the
978    /// corresponding channel has hung up.
979    ///
980    /// This function will always block the current thread if there is no data
981    /// available and it's possible for more data to be sent (at least one sender
982    /// still exists). Once a message is sent to the corresponding [`Sender`]
983    /// (or [`SyncSender`]), this receiver will wake up and return that
984    /// message.
985    ///
986    /// If the corresponding [`Sender`] has disconnected, or it disconnects while
987    /// this call is blocking, this call will wake up and return [`Err`] to
988    /// indicate that no more messages can ever be received on this channel.
989    /// However, since channels are buffered, messages sent before the disconnect
990    /// will still be properly received.
991    ///
992    /// # Examples
993    ///
994    /// ```
995    /// use std::sync::mpsc;
996    /// use std::thread;
997    ///
998    /// let (send, recv) = mpsc::channel();
999    /// let handle = thread::spawn(move || {
1000    ///     send.send(1u8).unwrap();
1001    /// });
1002    ///
1003    /// handle.join().unwrap();
1004    ///
1005    /// assert_eq!(Ok(1), recv.recv());
1006    /// ```
1007    ///
1008    /// Buffering behavior:
1009    ///
1010    /// ```
1011    /// use std::sync::mpsc;
1012    /// use std::thread;
1013    /// use std::sync::mpsc::RecvError;
1014    ///
1015    /// let (send, recv) = mpsc::channel();
1016    /// let handle = thread::spawn(move || {
1017    ///     send.send(1u8).unwrap();
1018    ///     send.send(2).unwrap();
1019    ///     send.send(3).unwrap();
1020    ///     drop(send);
1021    /// });
1022    ///
1023    /// // wait for the thread to join so we ensure the sender is dropped
1024    /// handle.join().unwrap();
1025    ///
1026    /// assert_eq!(Ok(1), recv.recv());
1027    /// assert_eq!(Ok(2), recv.recv());
1028    /// assert_eq!(Ok(3), recv.recv());
1029    /// assert_eq!(Err(RecvError), recv.recv());
1030    /// ```
1031    #[stable(feature = "rust1", since = "1.0.0")]
1032    pub fn recv(&self) -> Result<T, RecvError> {
1033        self.inner.recv()
1034    }
1035
1036    /// Attempts to wait for a value on this receiver, returning an error if the
1037    /// corresponding channel has hung up, or if it waits more than `timeout`.
1038    ///
1039    /// This function will always block the current thread if there is no data
1040    /// available and it's possible for more data to be sent (at least one sender
1041    /// still exists). Once a message is sent to the corresponding [`Sender`]
1042    /// (or [`SyncSender`]), this receiver will wake up and return that
1043    /// message.
1044    ///
1045    /// If the corresponding [`Sender`] has disconnected, or it disconnects while
1046    /// this call is blocking, this call will wake up and return [`Err`] to
1047    /// indicate that no more messages can ever be received on this channel.
1048    /// However, since channels are buffered, messages sent before the disconnect
1049    /// will still be properly received.
1050    ///
1051    /// # Examples
1052    ///
1053    /// Successfully receiving value before encountering timeout:
1054    ///
1055    /// ```no_run
1056    /// use std::thread;
1057    /// use std::time::Duration;
1058    /// use std::sync::mpsc;
1059    ///
1060    /// let (send, recv) = mpsc::channel();
1061    ///
1062    /// thread::spawn(move || {
1063    ///     send.send('a').unwrap();
1064    /// });
1065    ///
1066    /// assert_eq!(
1067    ///     recv.recv_timeout(Duration::from_millis(400)),
1068    ///     Ok('a')
1069    /// );
1070    /// ```
1071    ///
1072    /// Receiving an error upon reaching timeout:
1073    ///
1074    /// ```no_run
1075    /// use std::thread;
1076    /// use std::time::Duration;
1077    /// use std::sync::mpsc;
1078    ///
1079    /// let (send, recv) = mpsc::channel();
1080    ///
1081    /// thread::spawn(move || {
1082    ///     thread::sleep(Duration::from_millis(800));
1083    ///     send.send('a').unwrap();
1084    /// });
1085    ///
1086    /// assert_eq!(
1087    ///     recv.recv_timeout(Duration::from_millis(400)),
1088    ///     Err(mpsc::RecvTimeoutError::Timeout)
1089    /// );
1090    /// ```
1091    #[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
1092    pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> {
1093        self.inner.recv_timeout(timeout)
1094    }
1095
1096    /// Attempts to wait for a value on this receiver, returning an error if the
1097    /// corresponding channel has hung up, or if `deadline` is reached.
1098    ///
1099    /// This function will always block the current thread if there is no data
1100    /// available and it's possible for more data to be sent. Once a message is
1101    /// sent to the corresponding [`Sender`] (or [`SyncSender`]), then this
1102    /// receiver will wake up and return that message.
1103    ///
1104    /// If the corresponding [`Sender`] has disconnected, or it disconnects while
1105    /// this call is blocking, this call will wake up and return [`Err`] to
1106    /// indicate that no more messages can ever be received on this channel.
1107    /// However, since channels are buffered, messages sent before the disconnect
1108    /// will still be properly received.
1109    ///
1110    /// # Examples
1111    ///
1112    /// Successfully receiving value before reaching deadline:
1113    ///
1114    /// ```no_run
1115    /// #![feature(deadline_api)]
1116    /// use std::thread;
1117    /// use std::time::{Duration, Instant};
1118    /// use std::sync::mpsc;
1119    ///
1120    /// let (send, recv) = mpsc::channel();
1121    ///
1122    /// thread::spawn(move || {
1123    ///     send.send('a').unwrap();
1124    /// });
1125    ///
1126    /// assert_eq!(
1127    ///     recv.recv_deadline(Instant::now() + Duration::from_millis(400)),
1128    ///     Ok('a')
1129    /// );
1130    /// ```
1131    ///
1132    /// Receiving an error upon reaching deadline:
1133    ///
1134    /// ```no_run
1135    /// #![feature(deadline_api)]
1136    /// use std::thread;
1137    /// use std::time::{Duration, Instant};
1138    /// use std::sync::mpsc;
1139    ///
1140    /// let (send, recv) = mpsc::channel();
1141    ///
1142    /// thread::spawn(move || {
1143    ///     thread::sleep(Duration::from_millis(800));
1144    ///     send.send('a').unwrap();
1145    /// });
1146    ///
1147    /// assert_eq!(
1148    ///     recv.recv_deadline(Instant::now() + Duration::from_millis(400)),
1149    ///     Err(mpsc::RecvTimeoutError::Timeout)
1150    /// );
1151    /// ```
1152    #[unstable(feature = "deadline_api", issue = "46316")]
1153    pub fn recv_deadline(&self, deadline: Instant) -> Result<T, RecvTimeoutError> {
1154        self.inner.recv_deadline(deadline)
1155    }
1156
1157    /// Returns an iterator that will block waiting for messages, but never
1158    /// [`panic!`]. It will return [`None`] when the channel has hung up.
1159    ///
1160    /// # Examples
1161    ///
1162    /// ```rust
1163    /// use std::sync::mpsc::channel;
1164    /// use std::thread;
1165    ///
1166    /// let (send, recv) = channel();
1167    ///
1168    /// thread::spawn(move || {
1169    ///     send.send(1).unwrap();
1170    ///     send.send(2).unwrap();
1171    ///     send.send(3).unwrap();
1172    /// });
1173    ///
1174    /// let mut iter = recv.iter();
1175    /// assert_eq!(iter.next(), Some(1));
1176    /// assert_eq!(iter.next(), Some(2));
1177    /// assert_eq!(iter.next(), Some(3));
1178    /// assert_eq!(iter.next(), None);
1179    /// ```
1180    #[stable(feature = "rust1", since = "1.0.0")]
1181    pub fn iter(&self) -> Iter<'_, T> {
1182        Iter { rx: self }
1183    }
1184
1185    /// Returns an iterator that will attempt to yield all pending values.
1186    /// It will return `None` if there are no more pending values or if the
1187    /// channel has hung up. The iterator will never [`panic!`] or block the
1188    /// user by waiting for values.
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```no_run
1193    /// use std::sync::mpsc::channel;
1194    /// use std::thread;
1195    /// use std::time::Duration;
1196    ///
1197    /// let (sender, receiver) = channel();
1198    ///
1199    /// // nothing is in the buffer yet
1200    /// assert!(receiver.try_iter().next().is_none());
1201    ///
1202    /// thread::spawn(move || {
1203    ///     thread::sleep(Duration::from_secs(1));
1204    ///     sender.send(1).unwrap();
1205    ///     sender.send(2).unwrap();
1206    ///     sender.send(3).unwrap();
1207    /// });
1208    ///
1209    /// // nothing is in the buffer yet
1210    /// assert!(receiver.try_iter().next().is_none());
1211    ///
1212    /// // block for two seconds
1213    /// thread::sleep(Duration::from_secs(2));
1214    ///
1215    /// let mut iter = receiver.try_iter();
1216    /// assert_eq!(iter.next(), Some(1));
1217    /// assert_eq!(iter.next(), Some(2));
1218    /// assert_eq!(iter.next(), Some(3));
1219    /// assert_eq!(iter.next(), None);
1220    /// ```
1221    #[stable(feature = "receiver_try_iter", since = "1.15.0")]
1222    pub fn try_iter(&self) -> TryIter<'_, T> {
1223        TryIter { rx: self }
1224    }
1225
1226    /// Returns `true` if the channel is disconnected.
1227    ///
1228    /// Note that a return value of `false` does not guarantee the channel will
1229    /// remain connected. The channel may be disconnected immediately after this method
1230    /// returns, so a subsequent [`Receiver::recv`] may still fail with [`RecvError`].
1231    ///
1232    /// # Examples
1233    ///
1234    /// ```
1235    /// #![feature(mpsc_is_disconnected)]
1236    ///
1237    /// use std::sync::mpsc::channel;
1238    ///
1239    /// let (tx, rx) = channel::<i32>();
1240    /// assert!(!rx.is_disconnected());
1241    /// drop(tx);
1242    /// assert!(rx.is_disconnected());
1243    /// ```
1244    #[unstable(feature = "mpsc_is_disconnected", issue = "153668")]
1245    pub fn is_disconnected(&self) -> bool {
1246        self.inner.is_disconnected()
1247    }
1248
1249    /// Returns `true` if the channel is empty.
1250    ///
1251    /// Note: Zero-capacity channels are always empty.
1252    ///
1253    /// # Examples
1254    ///
1255    /// ```
1256    /// #![feature(mpsc_channel_len)]
1257    ///
1258    /// use std::sync::mpsc;
1259    /// use std::thread;
1260    ///
1261    /// let (send, recv) = mpsc::channel();
1262    ///
1263    /// assert!(recv.is_empty());
1264    ///
1265    /// let handle = thread::spawn(move || {
1266    ///     send.send(1u8).unwrap();
1267    /// });
1268    ///
1269    /// handle.join().unwrap();
1270    ///
1271    /// assert!(!recv.is_empty());
1272    /// ```
1273    #[unstable(feature = "mpsc_channel_len", issue = "165247")]
1274    pub fn is_empty(&self) -> bool {
1275        self.inner.is_empty()
1276    }
1277
1278    /// Returns the number of messages in the channel.
1279    ///
1280    /// # Examples
1281    ///
1282    /// ```
1283    /// #![feature(mpsc_channel_len)]
1284    ///
1285    /// use std::sync::mpsc;
1286    ///
1287    /// let (tx, rx) = mpsc::channel();
1288    ///
1289    /// assert_eq!(rx.len(), 0);
1290    ///
1291    /// tx.send(1u8).unwrap();
1292    /// tx.send(2u8).unwrap();
1293    /// assert_eq!(rx.len(), 2);
1294    ///
1295    /// rx.recv().unwrap();
1296    /// assert_eq!(rx.len(), 1);
1297    /// ```
1298    #[unstable(feature = "mpsc_channel_len", issue = "165247")]
1299    pub fn len(&self) -> usize {
1300        self.inner.len()
1301    }
1302}
1303
1304#[stable(feature = "rust1", since = "1.0.0")]
1305impl<'a, T> Iterator for Iter<'a, T> {
1306    type Item = T;
1307
1308    fn next(&mut self) -> Option<T> {
1309        self.rx.recv().ok()
1310    }
1311}
1312
1313#[stable(feature = "receiver_try_iter", since = "1.15.0")]
1314impl<'a, T> Iterator for TryIter<'a, T> {
1315    type Item = T;
1316
1317    fn next(&mut self) -> Option<T> {
1318        self.rx.try_recv().ok()
1319    }
1320}
1321
1322#[stable(feature = "receiver_into_iter", since = "1.1.0")]
1323impl<'a, T> IntoIterator for &'a Receiver<T> {
1324    type Item = T;
1325    type IntoIter = Iter<'a, T>;
1326
1327    fn into_iter(self) -> Iter<'a, T> {
1328        self.iter()
1329    }
1330}
1331
1332#[stable(feature = "receiver_into_iter", since = "1.1.0")]
1333impl<T> Iterator for IntoIter<T> {
1334    type Item = T;
1335    fn next(&mut self) -> Option<T> {
1336        self.rx.recv().ok()
1337    }
1338}
1339
1340#[stable(feature = "receiver_into_iter", since = "1.1.0")]
1341impl<T> IntoIterator for Receiver<T> {
1342    type Item = T;
1343    type IntoIter = IntoIter<T>;
1344
1345    fn into_iter(self) -> IntoIter<T> {
1346        IntoIter { rx: self }
1347    }
1348}
1349
1350#[stable(feature = "mpsc_debug", since = "1.8.0")]
1351impl<T> fmt::Debug for Receiver<T> {
1352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1353        f.debug_struct("Receiver").finish_non_exhaustive()
1354    }
1355}
1356
1357#[stable(feature = "rust1", since = "1.0.0")]
1358impl<T> fmt::Debug for SendError<T> {
1359    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1360        f.debug_struct("SendError").finish_non_exhaustive()
1361    }
1362}
1363
1364#[stable(feature = "rust1", since = "1.0.0")]
1365impl<T> fmt::Display for SendError<T> {
1366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1367        "sending on a closed channel".fmt(f)
1368    }
1369}
1370
1371#[stable(feature = "rust1", since = "1.0.0")]
1372impl<T> error::Error for SendError<T> {}
1373
1374#[stable(feature = "rust1", since = "1.0.0")]
1375impl<T> fmt::Debug for TrySendError<T> {
1376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1377        match *self {
1378            TrySendError::Full(..) => f.debug_tuple("TrySendError::Full").finish_non_exhaustive(),
1379            TrySendError::Disconnected(..) => {
1380                f.debug_tuple("TrySendError::Disconnected").finish_non_exhaustive()
1381            }
1382        }
1383    }
1384}
1385
1386#[stable(feature = "rust1", since = "1.0.0")]
1387impl<T> fmt::Display for TrySendError<T> {
1388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1389        match *self {
1390            TrySendError::Full(..) => "sending on a full channel".fmt(f),
1391            TrySendError::Disconnected(..) => "sending on a closed channel".fmt(f),
1392        }
1393    }
1394}
1395
1396#[stable(feature = "rust1", since = "1.0.0")]
1397impl<T> error::Error for TrySendError<T> {}
1398
1399#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
1400impl<T> From<SendError<T>> for TrySendError<T> {
1401    /// Converts a `SendError<T>` into a `TrySendError<T>`.
1402    ///
1403    /// This conversion always returns a `TrySendError::Disconnected` containing the data in the `SendError<T>`.
1404    ///
1405    /// No data is allocated on the heap.
1406    fn from(err: SendError<T>) -> TrySendError<T> {
1407        match err {
1408            SendError(t) => TrySendError::Disconnected(t),
1409        }
1410    }
1411}
1412
1413#[stable(feature = "rust1", since = "1.0.0")]
1414impl fmt::Display for RecvError {
1415    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1416        "receiving on a closed channel".fmt(f)
1417    }
1418}
1419
1420#[stable(feature = "rust1", since = "1.0.0")]
1421impl error::Error for RecvError {}
1422
1423#[stable(feature = "rust1", since = "1.0.0")]
1424impl fmt::Display for TryRecvError {
1425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1426        match *self {
1427            TryRecvError::Empty => "receiving on an empty channel".fmt(f),
1428            TryRecvError::Disconnected => "receiving on a closed channel".fmt(f),
1429        }
1430    }
1431}
1432
1433#[stable(feature = "rust1", since = "1.0.0")]
1434impl error::Error for TryRecvError {}
1435
1436#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
1437impl From<RecvError> for TryRecvError {
1438    /// Converts a `RecvError` into a `TryRecvError`.
1439    ///
1440    /// This conversion always returns `TryRecvError::Disconnected`.
1441    ///
1442    /// No data is allocated on the heap.
1443    fn from(err: RecvError) -> TryRecvError {
1444        match err {
1445            RecvError => TryRecvError::Disconnected,
1446        }
1447    }
1448}
1449
1450#[stable(feature = "mpsc_recv_timeout_error", since = "1.15.0")]
1451impl fmt::Display for RecvTimeoutError {
1452    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453        match *self {
1454            RecvTimeoutError::Timeout => "timed out waiting on channel".fmt(f),
1455            RecvTimeoutError::Disconnected => "channel is empty and sending half is closed".fmt(f),
1456        }
1457    }
1458}
1459
1460#[stable(feature = "mpsc_recv_timeout_error", since = "1.15.0")]
1461impl error::Error for RecvTimeoutError {}
1462
1463#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
1464impl From<RecvError> for RecvTimeoutError {
1465    /// Converts a `RecvError` into a `RecvTimeoutError`.
1466    ///
1467    /// This conversion always returns `RecvTimeoutError::Disconnected`.
1468    ///
1469    /// No data is allocated on the heap.
1470    fn from(err: RecvError) -> RecvTimeoutError {
1471        match err {
1472            RecvError => RecvTimeoutError::Disconnected,
1473        }
1474    }
1475}