Skip to content

Commit e934a5e

Browse files
committed
Safe arithmetic ops
1 parent 6664f4b commit e934a5e

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/task/blocking.rs

+12-5
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ lazy_static! {
136136

137137
/// Sliding window for pool task frequency calculation
138138
static ref FREQ_QUEUE: Mutex<VecDeque<u64>> = {
139-
Mutex::new(VecDeque::with_capacity(FREQUENCY_QUEUE_SIZE + 1))
139+
Mutex::new(VecDeque::with_capacity(FREQUENCY_QUEUE_SIZE.saturating_add(1)))
140140
};
141141

142142
/// Dynamic pool thread count variable
@@ -196,7 +196,7 @@ fn scale_pool() {
196196

197197
// Add seen frequency data to the frequency histogram.
198198
freq_queue.push_back(frequency);
199-
if freq_queue.len() == FREQUENCY_QUEUE_SIZE + 1 {
199+
if freq_queue.len() == FREQUENCY_QUEUE_SIZE.saturating_add(1) {
200200
freq_queue.pop_front();
201201
}
202202

@@ -255,12 +255,14 @@ fn create_blocking_thread() {
255255
// background noise.
256256
//
257257
// Generate a simple random number of milliseconds
258-
let rand_sleep_ms = u64::from(random(10_000));
258+
let rand_sleep_ms = 1000_u64
259+
.checked_add(u64::from(random(10_000)))
260+
.expect("shouldn't overflow");
259261

260262
let _ = thread::Builder::new()
261263
.name("async-blocking-driver-dynamic".to_string())
262264
.spawn(move || {
263-
let wait_limit = Duration::from_millis(1000 + rand_sleep_ms);
265+
let wait_limit = Duration::from_millis(rand_sleep_ms);
264266

265267
// Adjust the pool size counter before and after spawn
266268
*POOL_SIZE.lock().unwrap() += 1;
@@ -276,7 +278,12 @@ fn create_blocking_thread() {
276278
// Also, some systems have it(like macOS), and some don't(Linux).
277279
// This case expected not to happen.
278280
// But when happened this shouldn't throw a panic.
279-
MAX_THREADS.store(*POOL_SIZE.lock().unwrap() - 1, Ordering::SeqCst);
281+
let guarded_count = POOL_SIZE
282+
.lock()
283+
.unwrap()
284+
.checked_sub(1)
285+
.expect("shouldn't underflow");
286+
MAX_THREADS.store(guarded_count, Ordering::SeqCst);
280287
}
281288
_ => eprintln!(
282289
"cannot start a dynamic thread driving blocking tasks: {}",

0 commit comments

Comments
 (0)