From a6051a61ec5c96113f4b543de3ec55431695347a Mon Sep 17 00:00:00 2001 From: Blas Rodriguez Irizar Date: Wed, 2 Dec 2020 22:58:28 +0100 Subject: sync: make add_permits panic with usize::MAX >> 3 permits (#3188) --- tokio/src/sync/batch_semaphore.rs | 4 ++-- tokio/tests/sync_semaphore.rs | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/tokio/src/sync/batch_semaphore.rs b/tokio/src/sync/batch_semaphore.rs index 0b50e4f7..8736971a 100644 --- a/tokio/src/sync/batch_semaphore.rs +++ b/tokio/src/sync/batch_semaphore.rs @@ -253,9 +253,9 @@ impl Semaphore { } if rem > 0 && is_empty { - let permits = rem << Self::PERMIT_SHIFT; + let permits = rem; assert!( - permits < Self::MAX_PERMITS, + permits <= Self::MAX_PERMITS, "cannot add more than MAX_PERMITS permits ({})", Self::MAX_PERMITS ); diff --git a/tokio/tests/sync_semaphore.rs b/tokio/tests/sync_semaphore.rs index 1cb0c749..a33b878b 100644 --- a/tokio/tests/sync_semaphore.rs +++ b/tokio/tests/sync_semaphore.rs @@ -79,3 +79,17 @@ async fn stresstest() { let _p5 = sem.try_acquire().unwrap(); assert!(sem.try_acquire().is_err()); } + +#[test] +fn add_max_amount_permits() { + let s = tokio::sync::Semaphore::new(0); + s.add_permits(usize::MAX >> 3); + assert_eq!(s.available_permits(), usize::MAX >> 3); +} + +#[test] +#[should_panic] +fn add_more_than_max_amount_permits() { + let s = tokio::sync::Semaphore::new(1); + s.add_permits(usize::MAX >> 3); +} -- cgit v1.2.3