| 1 |
mod level; |
| 2 |
pub(crate) use self::level::Expiration; |
| 3 |
use self::level::Level; |
| 4 |
|
| 5 |
mod stack; |
| 6 |
pub(crate) use self::stack::Stack; |
| 7 |
|
| 8 |
use std::borrow::Borrow; |
| 9 |
use std::fmt::Debug; |
| 10 |
use std::usize; |
| 11 |
|
| 12 |
/// Timing wheel implementation. |
| 13 |
/// |
| 14 |
/// This type provides the hashed timing wheel implementation that backs `Timer` |
| 15 |
/// and `DelayQueue`. |
| 16 |
/// |
| 17 |
/// The structure is generic over `T: Stack`. This allows handling timeout data |
| 18 |
/// being stored on the heap or in a slab. In order to support the latter case, |
| 19 |
/// the slab must be passed into each function allowing the implementation to |
| 20 |
/// lookup timer entries. |
| 21 |
/// |
| 22 |
/// See `Timer` documentation for some implementation notes. |
| 23 |
#[derive(Debug)] |
| 24 |
pub(crate) struct Wheel<T> { |
| 25 |
/// The number of milliseconds elapsed since the wheel started. |
| 26 |
elapsed: u64, |
| 27 |
|
| 28 |
/// Timer wheel. |
| 29 |
/// |
| 30 |
/// Levels: |
| 31 |
/// |
| 32 |
/// * 1 ms slots / 64 ms range |
| 33 |
/// * 64 ms slots / ~ 4 sec range |
| 34 |
/// * ~ 4 sec slots / ~ 4 min range |
| 35 |
/// * ~ 4 min slots / ~ 4 hr range |
| 36 |
/// * ~ 4 hr slots / ~ 12 day range |
| 37 |
/// * ~ 12 day slots / ~ 2 yr range |
| 38 |
levels: Vec<Level<T>>, |
| 39 |
} |
| 40 |
|
| 41 |
/// Number of levels. Each level has 64 slots. By using 6 levels with 64 slots |
| 42 |
/// each, the timer is able to track time up to 2 years into the future with a |
| 43 |
/// precision of 1 millisecond. |
| 44 |
const NUM_LEVELS: usize = 6; |
| 45 |
|
| 46 |
/// The maximum duration of a delay |
| 47 |
const MAX_DURATION: u64 = (1 << (6 * NUM_LEVELS)) - 1; |
| 48 |
|
| 49 |
#[derive(Debug)] |
| 50 |
pub(crate) enum InsertError { |
| 51 |
Elapsed, |
| 52 |
Invalid, |
| 53 |
} |
| 54 |
|
| 55 |
impl<T> Wheel<T> |
| 56 |
where |
| 57 |
T: Stack, |
| 58 |
{ |
| 59 |
/// Create a new timing wheel |
| 60 |
pub(crate) fn new() -> Wheel<T> { |
| 61 |
let levels = (0..NUM_LEVELS).map(Level::new).collect(); |
| 62 |
|
| 63 |
Wheel { elapsed: 0, levels } |
| 64 |
} |
| 65 |
|
| 66 |
/// Return the number of milliseconds that have elapsed since the timing |
| 67 |
/// wheel's creation. |
| 68 |
pub(crate) fn elapsed(&self) -> u64 { |
| 69 |
self.elapsed |
| 70 |
} |
| 71 |
|
| 72 |
/// Insert an entry into the timing wheel. |
| 73 |
/// |
| 74 |
/// # Arguments |
| 75 |
/// |
| 76 |
/// * `when`: is the instant at which the entry should be fired. It is |
| 77 |
/// represented as the number of milliseconds since the creation |
| 78 |
/// of the timing wheel. |
| 79 |
/// |
| 80 |
/// * `item`: The item to insert into the wheel. |
| 81 |
/// |
| 82 |
/// * `store`: The slab or `()` when using heap storage. |
| 83 |
/// |
| 84 |
/// # Return |
| 85 |
/// |
| 86 |
/// Returns `Ok` when the item is successfully inserted, `Err` otherwise. |
| 87 |
/// |
| 88 |
/// `Err(Elapsed)` indicates that `when` represents an instant that has |
| 89 |
/// already passed. In this case, the caller should fire the timeout |
| 90 |
/// immediately. |
| 91 |
/// |
| 92 |
/// `Err(Invalid)` indicates an invalid `when` argument as been supplied. |
| 93 |
pub(crate) fn insert( |
| 94 |
&mut self, |
| 95 |
when: u64, |
| 96 |
item: T::Owned, |
| 97 |
store: &mut T::Store, |
| 98 |
) -> Result<(), (T::Owned, InsertError)> { |
| 99 |
if when <= self.elapsed { |
| 100 |
return Err((item, InsertError::Elapsed)); |
| 101 |
} else if when - self.elapsed > MAX_DURATION { |
| 102 |
return Err((item, InsertError::Invalid)); |
| 103 |
} |
| 104 |
|
| 105 |
// Get the level at which the entry should be stored |
| 106 |
let level = self.level_for(when); |
| 107 |
|
| 108 |
self.levels[level].add_entry(when, item, store); |
| 109 |
|
| 110 |
debug_assert!({ |
| 111 |
self.levels[level] |
| 112 |
.next_expiration(self.elapsed) |
| 113 |
.map(|e| e.deadline >= self.elapsed) |
| 114 |
.unwrap_or(true) |
| 115 |
}); |
| 116 |
|
| 117 |
Ok(()) |
| 118 |
} |
| 119 |
|
| 120 |
/// Remove `item` from the timing wheel. |
| 121 |
pub(crate) fn remove(&mut self, item: &T::Borrowed, store: &mut T::Store) { |
| 122 |
let when = T::when(item, store); |
| 123 |
|
| 124 |
assert!( |
| 125 |
self.elapsed <= when, |
| 126 |
"elapsed={}; when={}", |
| 127 |
self.elapsed, |
| 128 |
when |
| 129 |
); |
| 130 |
|
| 131 |
let level = self.level_for(when); |
| 132 |
|
| 133 |
self.levels[level].remove_entry(when, item, store); |
| 134 |
} |
| 135 |
|
| 136 |
/// Instant at which to poll |
| 137 |
pub(crate) fn poll_at(&self) -> Option<u64> { |
| 138 |
self.next_expiration().map(|expiration| expiration.deadline) |
| 139 |
} |
| 140 |
|
| 141 |
/// Advances the timer up to the instant represented by `now`. |
| 142 |
pub(crate) fn poll(&mut self, now: u64, store: &mut T::Store) -> Option<T::Owned> { |
| 143 |
loop { |
| 144 |
let expiration = self.next_expiration().and_then(|expiration| { |
| 145 |
if expiration.deadline > now { |
| 146 |
None |
| 147 |
} else { |
| 148 |
Some(expiration) |
| 149 |
} |
| 150 |
}); |
| 151 |
|
| 152 |
match expiration { |
| 153 |
Some(ref expiration) => { |
| 154 |
if let Some(item) = self.poll_expiration(expiration, store) { |
| 155 |
return Some(item); |
| 156 |
} |
| 157 |
|
| 158 |
self.set_elapsed(expiration.deadline); |
| 159 |
} |
| 160 |
None => { |
| 161 |
// in this case the poll did not indicate an expiration |
| 162 |
// _and_ we were not able to find a next expiration in |
| 163 |
// the current list of timers. advance to the poll's |
| 164 |
// current time and do nothing else. |
| 165 |
self.set_elapsed(now); |
| 166 |
return None; |
| 167 |
} |
| 168 |
} |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
/// Returns the instant at which the next timeout expires. |
| 173 |
fn next_expiration(&self) -> Option<Expiration> { |
| 174 |
// Check all levels |
| 175 |
for level in 0..NUM_LEVELS { |
| 176 |
if let Some(expiration) = self.levels[level].next_expiration(self.elapsed) { |
| 177 |
// There cannot be any expirations at a higher level that happen |
| 178 |
// before this one. |
| 179 |
debug_assert!(self.no_expirations_before(level + 1, expiration.deadline)); |
| 180 |
|
| 181 |
return Some(expiration); |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
None |
| 186 |
} |
| 187 |
|
| 188 |
/// Used for debug assertions |
| 189 |
fn no_expirations_before(&self, start_level: usize, before: u64) -> bool { |
| 190 |
let mut res = true; |
| 191 |
|
| 192 |
for l2 in start_level..NUM_LEVELS { |
| 193 |
if let Some(e2) = self.levels[l2].next_expiration(self.elapsed) { |
| 194 |
if e2.deadline < before { |
| 195 |
res = false; |
| 196 |
} |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
res |
| 201 |
} |
| 202 |
|
| 203 |
/// iteratively find entries that are between the wheel's current |
| 204 |
/// time and the expiration time. for each in that population either |
| 205 |
/// return it for notification (in the case of the last level) or tier |
| 206 |
/// it down to the next level (in all other cases). |
| 207 |
pub(crate) fn poll_expiration( |
| 208 |
&mut self, |
| 209 |
expiration: &Expiration, |
| 210 |
store: &mut T::Store, |
| 211 |
) -> Option<T::Owned> { |
| 212 |
while let Some(item) = self.pop_entry(expiration, store) { |
| 213 |
if expiration.level == 0 { |
| 214 |
debug_assert_eq!(T::when(item.borrow(), store), expiration.deadline); |
| 215 |
|
| 216 |
return Some(item); |
| 217 |
} else { |
| 218 |
let when = T::when(item.borrow(), store); |
| 219 |
|
| 220 |
let next_level = expiration.level - 1; |
| 221 |
|
| 222 |
self.levels[next_level].add_entry(when, item, store); |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
None |
| 227 |
} |
| 228 |
|
| 229 |
fn set_elapsed(&mut self, when: u64) { |
| 230 |
assert!( |
| 231 |
self.elapsed <= when, |
| 232 |
"elapsed={:?}; when={:?}", |
| 233 |
self.elapsed, |
| 234 |
when |
| 235 |
); |
| 236 |
|
| 237 |
if when > self.elapsed { |
| 238 |
self.elapsed = when; |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
fn pop_entry(&mut self, expiration: &Expiration, store: &mut T::Store) -> Option<T::Owned> { |
| 243 |
self.levels[expiration.level].pop_entry_slot(expiration.slot, store) |
| 244 |
} |
| 245 |
|
| 246 |
fn level_for(&self, when: u64) -> usize { |
| 247 |
level_for(self.elapsed, when) |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
fn level_for(elapsed: u64, when: u64) -> usize { |
| 252 |
const SLOT_MASK: u64 = (1 << 6) - 1; |
| 253 |
|
| 254 |
// Mask in the trailing bits ignored by the level calculation in order to cap |
| 255 |
// the possible leading zeros |
| 256 |
let masked = elapsed ^ when | SLOT_MASK; |
| 257 |
|
| 258 |
let leading_zeros = masked.leading_zeros() as usize; |
| 259 |
let significant = 63 - leading_zeros; |
| 260 |
significant / 6 |
| 261 |
} |
| 262 |
|
| 263 |
#[cfg(all(test, not(loom)))] |
| 264 |
mod test { |
| 265 |
use super::*; |
| 266 |
|
| 267 |
#[test] |
| 268 |
fn test_level_for() { |
| 269 |
for pos in 0..64 { |
| 270 |
assert_eq!( |
| 271 |
0, |
| 272 |
level_for(0, pos), |
| 273 |
"level_for({}) -- binary = {:b}", |
| 274 |
pos, |
| 275 |
pos |
| 276 |
); |
| 277 |
} |
| 278 |
|
| 279 |
for level in 1..5 { |
| 280 |
for pos in level..64 { |
| 281 |
let a = pos * 64_usize.pow(level as u32); |
| 282 |
assert_eq!( |
| 283 |
level, |
| 284 |
level_for(0, a as u64), |
| 285 |
"level_for({}) -- binary = {:b}", |
| 286 |
a, |
| 287 |
a |
| 288 |
); |
| 289 |
|
| 290 |
if pos > level { |
| 291 |
let a = a - 1; |
| 292 |
assert_eq!( |
| 293 |
level, |
| 294 |
level_for(0, a as u64), |
| 295 |
"level_for({}) -- binary = {:b}", |
| 296 |
a, |
| 297 |
a |
| 298 |
); |
| 299 |
} |
| 300 |
|
| 301 |
if pos < 64 { |
| 302 |
let a = a + 1; |
| 303 |
assert_eq!( |
| 304 |
level, |
| 305 |
level_for(0, a as u64), |
| 306 |
"level_for({}) -- binary = {:b}", |
| 307 |
a, |
| 308 |
a |
| 309 |
); |
| 310 |
} |
| 311 |
} |
| 312 |
} |
| 313 |
} |
| 314 |
} |