Add KUnit coverage for Instant + Delta and Instant - Delta after the invariant-preserving arithmetic change. Test an in-range add/sub path, and the clamping paths used when CONFIG_RUST_OVERFLOW_CHECKS is disabled: a result below 0 clamps to 0, and a result above KTIME_MAX (i64::MAX) saturates at KTIME_MAX. The out-of-range panic paths under overflow checks are left for later should_panic support. Suggested-by: Andreas Hindborg Suggested-by: Miguel Ojeda Signed-off-by: Franklin-Qi --- rust/kernel/time.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs index 4ff65c74b5b5..5a251eb47bfe 100644 --- a/rust/kernel/time.rs +++ b/rust/kernel/time.rs @@ -1010,4 +1010,56 @@ fn to_jiffies_timeout_saturates() { let negative = Delta::from_nanos(i64::MIN).to_jiffies_timeout(); assert_eq!(negative.as_jiffies(), 0); } + + /// Build an [`Instant`] with a chosen nanosecond value for boundary tests. + /// + /// `ns` must be in `0..=KTIME_MAX` (`i64::MAX`). + fn instant_at(ns: i64) -> Instant { + Instant { + inner: ns, + _c: PhantomData, + } + } + + #[test] + fn instant_add_sub_delta_in_range() { + let t = instant_at(NSEC_PER_SEC); + + assert_eq!((t + Delta::from_secs(1)).as_nanos(), 2 * NSEC_PER_SEC); + assert_eq!((t - Delta::from_secs(1)).as_nanos(), 0); + } + + // Clamping only applies when overflow checks are disabled; with them enabled the + // out-of-range cases panic instead (covered manually / once `should_panic` lands). + #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))] + #[test] + fn instant_add_clamps_above_ktime_max() { + let t = instant_at(i64::MAX); + + assert_eq!((t + Delta::from_nanos(1)).as_nanos(), i64::MAX); + } + + #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))] + #[test] + fn instant_sub_clamps_below_zero() { + let t = instant_at(0); + + assert_eq!((t - Delta::from_nanos(1)).as_nanos(), 0); + } + + #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))] + #[test] + fn instant_add_negative_delta_clamps_below_zero() { + let t = instant_at(5); + + assert_eq!((t + Delta::from_nanos(-10)).as_nanos(), 0); + } + + #[cfg(not(CONFIG_RUST_OVERFLOW_CHECKS))] + #[test] + fn instant_sub_negative_delta_clamps_above_ktime_max() { + let t = instant_at(i64::MAX); + + assert_eq!((t - Delta::from_nanos(-1)).as_nanos(), i64::MAX); + } } -- 2.55.0