Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make reason for try_send errors clearer #864

Merged
merged 2 commits into from
Jan 23, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions tokio-sync/src/mpsc/bounded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,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 was_closed(&self) -> bool {
if let ErrorKind::Closed = self.kind {
true
} else {
false
}
}

/// Did the send fail because the channel was at capacity?
pub fn was_full(&self) -> bool {
jonhoo marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -28,7 +28,7 @@ pub struct 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 @@ -227,7 +227,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().was_full());

assert_eq!(rx.next().unwrap().unwrap(), "hello");

Expand Down Expand Up @@ -272,6 +272,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().was_closed());

assert_eq!(1, Arc::strong_count(&msg));
}

#[test]
fn unconsumed_messagers_are_dropped() {
let msg = Arc::new(());
Expand Down