From 28b983c4bc1f0041b59d590a55c6e4aafdf7b971 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Tue, 15 Feb 2022 18:26:07 +0100 Subject: [PATCH] time: use bit manipulation instead of modulo (#4480) time: resolve TODO ## Motivation Existing `TODO` comment in `src/time/driver/wheel/level.rs`. ## Solution `level_range()` always return a strictly positive power of 2. If `b` is a strictly positive power of 2, `a - (a % b)` is equal to `a & !(b - 1)`. --- tokio/src/time/driver/wheel/level.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tokio/src/time/driver/wheel/level.rs b/tokio/src/time/driver/wheel/level.rs index 7fd2266bb8e..878754177b9 100644 --- a/tokio/src/time/driver/wheel/level.rs +++ b/tokio/src/time/driver/wheel/level.rs @@ -143,8 +143,9 @@ impl Level { let level_range = level_range(self.level); let slot_range = slot_range(self.level); - // TODO: This can probably be simplified w/ power of 2 math - let level_start = now - (now % level_range); + // Compute the start date of the current level by masking the low bits + // of `now` (`level_range` is a power of 2). + let level_start = now & !(level_range - 1); let mut deadline = level_start + slot as u64 * slot_range; if deadline <= now {