1
Fork 0
mirror of https://github.com/RGBCube/superfreq synced 2025-07-27 17:07:44 +00:00

daemon: use u128 arithmetic to prevent overflow in polling interval calc

Overflows are unlikely to happen, but easy to prevent. Let's fix it while we're at it.
This commit is contained in:
NotAShelf 2025-05-18 08:27:53 +03:00
parent 34862b28e1
commit 2efc0e1a6b
No known key found for this signature in database
GPG key ID: 29D95B64378DB4BF

View file

@ -126,8 +126,10 @@ fn compute_new(params: &IntervalParams, system_history: &SystemHistory) -> u64 {
let blended_interval = if let Some(cached) = system_history.last_computed_interval { let blended_interval = if let Some(cached) = system_history.last_computed_interval {
// Use a weighted average: 70% previous value, 30% new value // Use a weighted average: 70% previous value, 30% new value
// This smooths out drastic changes in polling frequency // This smooths out drastic changes in polling frequency
// Use integer arithmetic to avoid precision loss with large interval values // XXX: Use u128 arithmetic to avoid overflow with large interval values
(cached * 7 + new_interval * 3) / 10 let result = (cached as u128 * 7 + new_interval as u128 * 3) / 10;
result as u64
} else { } else {
new_interval new_interval
}; };
@ -538,12 +540,19 @@ pub fn run_daemon(mut config: AppConfig, verbose: bool) -> Result<(), AppError>
); );
// Don't change the interval too dramatically at once // Don't change the interval too dramatically at once
if optimal_interval > current_poll_interval { match optimal_interval.cmp(&current_poll_interval) {
current_poll_interval = (current_poll_interval + optimal_interval) / 2; std::cmp::Ordering::Greater => {
} else if optimal_interval < current_poll_interval { current_poll_interval =
(current_poll_interval + optimal_interval) / 2;
}
std::cmp::Ordering::Less => {
current_poll_interval = current_poll_interval current_poll_interval = current_poll_interval
- ((current_poll_interval - optimal_interval) / 2).max(1); - ((current_poll_interval - optimal_interval) / 2).max(1);
} }
std::cmp::Ordering::Equal => {
// No change needed when they're equal
}
}
} else { } else {
debug!( debug!(
"Using cached optimal interval: {}s (no significant system change)", "Using cached optimal interval: {}s (no significant system change)",