Skip to content

Commit 0ec8986

Browse files
jonhoocarllerche
authored andcommitted
Make reason for try_send errors clearer (#864)
1 parent c6f8bdb commit 0ec8986

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

tokio-sync/src/mpsc/bounded.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,24 @@ impl<T> TrySendError<T> {
239239
pub fn into_inner(self) -> T {
240240
self.value
241241
}
242+
243+
/// Did the send fail because the channel has been closed?
244+
pub fn is_closed(&self) -> bool {
245+
if let ErrorKind::Closed = self.kind {
246+
true
247+
} else {
248+
false
249+
}
250+
}
251+
252+
/// Did the send fail because the channel was at capacity?
253+
pub fn is_full(&self) -> bool {
254+
if let ErrorKind::NoCapacity = self.kind {
255+
true
256+
} else {
257+
false
258+
}
259+
}
242260
}
243261

244262
impl<T: fmt::Debug> fmt::Display for TrySendError<T> {

tokio-sync/src/mpsc/unbounded.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ impl<T> fmt::Debug for UnboundedReceiver<T> {
4848
#[derive(Debug)]
4949
pub struct UnboundedSendError(());
5050

51-
/// Error returned by `UnboundedSender::try_send`.
51+
/// Returned by `UnboundedSender::try_send` when the channel has been closed.
5252
#[derive(Debug)]
5353
pub struct UnboundedTrySendError<T>(T);
5454

tokio-sync/tests/mpsc.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ fn try_send_fail() {
255255
tx.try_send("hello").unwrap();
256256

257257
// This should fail
258-
assert!(tx.try_send("fail").is_err());
258+
assert!(tx.try_send("fail").unwrap_err().is_full());
259259

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

@@ -300,6 +300,19 @@ fn dropping_rx_closes_channel() {
300300
assert_eq!(1, Arc::strong_count(&msg));
301301
}
302302

303+
#[test]
304+
fn dropping_rx_closes_channel_for_try() {
305+
let (mut tx, rx) = mpsc::channel(100);
306+
307+
let msg = Arc::new(());
308+
tx.try_send(msg.clone()).unwrap();
309+
310+
drop(rx);
311+
assert!(tx.try_send(msg.clone()).unwrap_err().is_closed());
312+
313+
assert_eq!(1, Arc::strong_count(&msg));
314+
}
315+
303316
#[test]
304317
fn unconsumed_messagers_are_dropped() {
305318
let msg = Arc::new(());

0 commit comments

Comments
 (0)