From 6589f235aebeaf1e060f70706d3698f3097acc57 Mon Sep 17 00:00:00 2001 From: kenoss Date: Thu, 21 Nov 2024 02:16:04 +0900 Subject: [PATCH 1/2] refactor: Simplify timeout calculation in Poll::poll() --- src/sys.rs | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/sys.rs b/src/sys.rs index 2efe6ab1..7a9d86a0 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -1,4 +1,10 @@ -use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc, time::Duration}; +use std::{ + cell::RefCell, + collections::HashMap, + rc::Rc, + sync::Arc, + time::{Duration, Instant}, +}; #[cfg(unix)] use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd as Borrowed, RawFd as Raw}; @@ -215,17 +221,15 @@ impl Poll { } pub(crate) fn poll(&self, mut timeout: Option) -> crate::Result> { - let now = std::time::Instant::now(); - // Adjust the timeout for the timers. - if let Some(next_timeout) = self.timers.borrow().next_deadline() { - if next_timeout <= now { - timeout = Some(Duration::ZERO); - } else if let Some(deadline) = timeout { - timeout = Some(std::cmp::min(deadline, next_timeout - now)); - } else { - timeout = Some(next_timeout - now); - } + let timeout2 = self + .timers + .borrow() + .next_deadline() + .map(|deadline| deadline.saturating_duration_since(Instant::now())); + timeout = match (timeout, timeout2) { + (Some(timeout), Some(timeout2)) => Some(timeout.min(timeout2)), + _ => timeout.or(timeout2), }; let mut events = self.events.borrow_mut(); @@ -263,8 +267,7 @@ impl Poll { drop(events); - // Update 'now' as some time may have elapsed in poll() - let now = std::time::Instant::now(); + let now = Instant::now(); let mut timers = self.timers.borrow_mut(); while let Some((_, token)) = timers.next_expired(now) { poll_events.push(PollEvent { From 973678905713402514f47fa593d5f083615ff817 Mon Sep 17 00:00:00 2001 From: kenoss Date: Fri, 22 Nov 2024 01:06:24 +0900 Subject: [PATCH 2/2] s/timeout2/next_timeout/ --- src/sys.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sys.rs b/src/sys.rs index 7a9d86a0..e56a140e 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -222,14 +222,14 @@ impl Poll { pub(crate) fn poll(&self, mut timeout: Option) -> crate::Result> { // Adjust the timeout for the timers. - let timeout2 = self + let next_timeout = self .timers .borrow() .next_deadline() .map(|deadline| deadline.saturating_duration_since(Instant::now())); - timeout = match (timeout, timeout2) { - (Some(timeout), Some(timeout2)) => Some(timeout.min(timeout2)), - _ => timeout.or(timeout2), + timeout = match (timeout, next_timeout) { + (Some(timeout), Some(next_timeout)) => Some(timeout.min(next_timeout)), + _ => timeout.or(next_timeout), }; let mut events = self.events.borrow_mut();