Replace subtraction of Instants and Durations with saturating subtractions (#12549)

# Description
Duration can not be negative, and an underflow causes a panic.

This should fix #12539 as from what I can tell that bug was caused in
`nu-explore:📟:events` from subtracting durations, but I figured
this might be more widespread, and saturating to zero generally makes
sense.

I also added the relevant clippy lint to try to prevent this from
happening in the future. I can't think of a reason we would ever want to
subtract durations without checking first.

cc @fdncred

# Tests + Formatting
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`
This commit is contained in:
Devyn Cairns
2024-04-17 05:25:16 -07:00
committed by GitHub
parent 410f3c5c8a
commit 13160b3ec3
7 changed files with 15 additions and 9 deletions

View File

@ -93,7 +93,7 @@ pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo>
let curr_res = pidrusage::<RUsageInfoV2>(pid).ok();
let curr_time = Instant::now();
let interval = curr_time - prev_time;
let interval = curr_time.saturating_duration_since(prev_time);
let ppid = curr_task.pbsd.pbi_ppid as i32;
let proc = ProcessInfo {
@ -383,7 +383,7 @@ impl ProcessInfo {
self.curr_task.ptinfo.pti_total_user + self.curr_task.ptinfo.pti_total_system;
let prev_time =
self.prev_task.ptinfo.pti_total_user + self.prev_task.ptinfo.pti_total_system;
let usage_ticks = curr_time - prev_time;
let usage_ticks = curr_time.saturating_sub(prev_time);
let interval_us = self.interval.as_micros();
let ticktime_us = mach_ticktime() / 1000.0;
usage_ticks as f64 * 100.0 * ticktime_us / interval_us as f64