From 80619115d3c9ae8cc22a9ccdd68c17f3b9070da2 Mon Sep 17 00:00:00 2001 From: Alejandro Candioti Date: Tue, 30 Jul 2024 22:10:51 -0700 Subject: [PATCH] On same deadline, items queued first have priority --- src/sources/timer.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/sources/timer.rs b/src/sources/timer.rs index b6331c9d..dd08da52 100644 --- a/src/sources/timer.rs +++ b/src/sources/timer.rs @@ -278,8 +278,11 @@ impl TimerWheel { impl std::cmp::Ord for TimeoutData { #[inline] fn cmp(&self, other: &Self) -> std::cmp::Ordering { - // earlier values have priority - self.deadline.cmp(&other.deadline).reverse() + // earlier values have priority, on same deadline items queued first have priority + self.deadline + .cmp(&other.deadline) + .then_with(|| self.counter.cmp(&other.counter)) + .reverse() } } @@ -381,6 +384,31 @@ mod tests { use crate::*; use std::time::Duration; + #[test] + fn timeout_data_cmp() { + let now = Instant::now(); + let timeout_now_0 = TimeoutData { + deadline: now, + token: RefCell::new(None), + counter: 0, + }; + let timeout_now_1 = TimeoutData { + deadline: now, + token: RefCell::new(None), + counter: 1, + }; + assert!(timeout_now_0 > timeout_now_1); + assert!(timeout_now_1 < timeout_now_0); + + let timeout_future_0 = TimeoutData { + deadline: now + Duration::from_millis(100), + token: RefCell::new(None), + counter: 0, + }; + assert!(timeout_now_1 > timeout_future_0); + assert!(timeout_future_0 < timeout_now_1); + } + #[test] fn simple_timer() { let mut event_loop = EventLoop::try_new().unwrap();