From 0ec8986b0bc60cc96e88ab72e4675d975fbc8f1c Mon Sep 17 00:00:00 2001 From: Jon Gjengset Date: Wed, 23 Jan 2019 18:06:24 -0500 Subject: [PATCH] Make reason for try_send errors clearer (#864) --- tokio-sync/src/mpsc/bounded.rs | 18 ++++++++++++++++++ tokio-sync/src/mpsc/unbounded.rs | 2 +- tokio-sync/tests/mpsc.rs | 15 ++++++++++++++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/tokio-sync/src/mpsc/bounded.rs b/tokio-sync/src/mpsc/bounded.rs index ad5d6eea4..f2954448e 100644 --- a/tokio-sync/src/mpsc/bounded.rs +++ b/tokio-sync/src/mpsc/bounded.rs @@ -239,6 +239,24 @@ impl TrySendError { pub fn into_inner(self) -> T { self.value } + + /// Did the send fail because the channel has been closed? + pub fn is_closed(&self) -> bool { + if let ErrorKind::Closed = self.kind { + true + } else { + false + } + } + + /// Did the send fail because the channel was at capacity? + pub fn is_full(&self) -> bool { + if let ErrorKind::NoCapacity = self.kind { + true + } else { + false + } + } } impl fmt::Display for TrySendError { diff --git a/tokio-sync/src/mpsc/unbounded.rs b/tokio-sync/src/mpsc/unbounded.rs index 1473c1b93..181ad5179 100644 --- a/tokio-sync/src/mpsc/unbounded.rs +++ b/tokio-sync/src/mpsc/unbounded.rs @@ -48,7 +48,7 @@ impl fmt::Debug for UnboundedReceiver { #[derive(Debug)] pub struct UnboundedSendError(()); -/// Error returned by `UnboundedSender::try_send`. +/// Returned by `UnboundedSender::try_send` when the channel has been closed. #[derive(Debug)] pub struct UnboundedTrySendError(T); diff --git a/tokio-sync/tests/mpsc.rs b/tokio-sync/tests/mpsc.rs index ce3fafc1d..5b184d4e2 100644 --- a/tokio-sync/tests/mpsc.rs +++ b/tokio-sync/tests/mpsc.rs @@ -255,7 +255,7 @@ fn try_send_fail() { tx.try_send("hello").unwrap(); // This should fail - assert!(tx.try_send("fail").is_err()); + assert!(tx.try_send("fail").unwrap_err().is_full()); assert_eq!(rx.next().unwrap().unwrap(), "hello"); @@ -300,6 +300,19 @@ fn dropping_rx_closes_channel() { assert_eq!(1, Arc::strong_count(&msg)); } +#[test] +fn dropping_rx_closes_channel_for_try() { + let (mut tx, rx) = mpsc::channel(100); + + let msg = Arc::new(()); + tx.try_send(msg.clone()).unwrap(); + + drop(rx); + assert!(tx.try_send(msg.clone()).unwrap_err().is_closed()); + + assert_eq!(1, Arc::strong_count(&msg)); +} + #[test] fn unconsumed_messagers_are_dropped() { let msg = Arc::new(());