Skip to content

Commit

Permalink
mpsc: ensure try_reserve error is consistent with try_send (#4119)
Browse files Browse the repository at this point in the history
  • Loading branch information
alanbriolat authored Sep 19, 2021
1 parent f1b8967 commit e9f6fae
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
6 changes: 4 additions & 2 deletions tokio/src/sync/mpsc/bounded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -851,7 +851,8 @@ impl<T> Sender<T> {
pub fn try_reserve(&self) -> Result<Permit<'_, T>, TrySendError<()>> {
match self.chan.semaphore().0.try_acquire(1) {
Ok(_) => {}
Err(_) => return Err(TrySendError::Full(())),
Err(TryAcquireError::Closed) => return Err(TrySendError::Closed(())),
Err(TryAcquireError::NoPermits) => return Err(TrySendError::Full(())),
}

Ok(Permit { chan: &self.chan })
Expand Down Expand Up @@ -915,7 +916,8 @@ impl<T> Sender<T> {
pub fn try_reserve_owned(self) -> Result<OwnedPermit<T>, TrySendError<Self>> {
match self.chan.semaphore().0.try_acquire(1) {
Ok(_) => {}
Err(_) => return Err(TrySendError::Full(self)),
Err(TryAcquireError::Closed) => return Err(TrySendError::Closed(self)),
Err(TryAcquireError::NoPermits) => return Err(TrySendError::Full(self)),
}

Ok(OwnedPermit {
Expand Down
16 changes: 9 additions & 7 deletions tokio/tests/sync_mpsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,13 +410,15 @@ fn dropping_rx_closes_channel_for_try() {

drop(rx);

{
let err = assert_err!(tx.try_send(msg.clone()));
match err {
TrySendError::Closed(..) => {}
_ => panic!(),
}
}
assert!(matches!(
tx.try_send(msg.clone()),
Err(TrySendError::Closed(_))
));
assert!(matches!(tx.try_reserve(), Err(TrySendError::Closed(_))));
assert!(matches!(
tx.try_reserve_owned(),
Err(TrySendError::Closed(_))
));

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

0 comments on commit e9f6fae

Please sign in to comment.