Skip to content

Commit

Permalink
Make reason for try_send errors clearer (#864)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonhoo authored and carllerche committed Jan 23, 2019
1 parent c6f8bdb commit 0ec8986
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
18 changes: 18 additions & 0 deletions tokio-sync/src/mpsc/bounded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,24 @@ impl<T> TrySendError<T> {
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<T: fmt::Debug> fmt::Display for TrySendError<T> {
Expand Down
2 changes: 1 addition & 1 deletion tokio-sync/src/mpsc/unbounded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl<T> fmt::Debug for UnboundedReceiver<T> {
#[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>(T);

Expand Down
15 changes: 14 additions & 1 deletion tokio-sync/tests/mpsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down Expand Up @@ -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(());
Expand Down

0 comments on commit 0ec8986

Please sign in to comment.