Re: [PATCH v3 1/2] rust: time: Implement Add<Delta>/Sub<Delta> for Instant

From: Daniel Almeida
Date: Tue Aug 26 2025 - 10:28:20 EST


Hi Lyude,


> On 20 Aug 2025, at 17:26, Lyude Paul <lyude@xxxxxxxxxx> wrote:
>
> In order to copy the behavior rust currently follows for basic arithmetic
> operations and panic if the result of an addition or subtraction results in
> a value that would violate the invariants of Instant, but only if the
> kernel has overflow checking for rust enabled.
>
> Signed-off-by: Lyude Paul <lyude@xxxxxxxxxx>
>
> ---
>
> V2:
> * Change behavior in ops::{Add,Sub}<Delta> so that we panic on overflows
> under the same conditions that arithmetic operations in rust would panic
> by default.
> V3:
> * Don't forget to update the commit message this time!
>
> rust/kernel/time.rs | 43 ++++++++++++++++++++++++++++++++++++++++++-
> 1 file changed, 42 insertions(+), 1 deletion(-)
>
> diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
> index 64c8dcf548d63..4bd7a8a009f3e 100644
> --- a/rust/kernel/time.rs
> +++ b/rust/kernel/time.rs
> @@ -25,6 +25,7 @@
> //! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h).
>
> use core::marker::PhantomData;
> +use core::ops;
>
> pub mod delay;
> pub mod hrtimer;
> @@ -202,7 +203,7 @@ pub(crate) fn as_nanos(&self) -> i64 {
> }
> }
>
> -impl<C: ClockSource> core::ops::Sub for Instant<C> {
> +impl<C: ClockSource> ops::Sub for Instant<C> {
> type Output = Delta;
>
> // By the type invariant, it never overflows.
> @@ -214,6 +215,46 @@ fn sub(self, other: Instant<C>) -> Delta {
> }
> }
>
> +impl<T: ClockSource> ops::Add<Delta> for Instant<T> {
> + type Output = Self;
> +
> + #[inline]
> + fn add(self, rhs: Delta) -> Self::Output {
> + // INVARIANT: With arithmetic over/underflow checks enabled, this will panic if we overflow
> + // (e.g. go above `KTIME_MAX`)
> + let res = self.inner + rhs.nanos;

Shouldn’t we clamp here instead of..
> +
> + // INVARIANT: With overflow checks enabled, we verify here that the value is >= 0
> + #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
> + assert!(res >= 0);

..relying on this?

> +
> + Self {
> + inner: res,
> + _c: PhantomData,
> + }
> + }
> +}
> +
> +impl<T: ClockSource> ops::Sub<Delta> for Instant<T> {
> + type Output = Self;
> +
> + #[inline]
> + fn sub(self, rhs: Delta) -> Self::Output {
> + // INVARIANT: With arithmetic over/underflow checks enabled, this will panic if we overflow
> + // (e.g. go above `KTIME_MAX`)
> + let res = self.inner - rhs.nanos;
> +
> + // INVARIANT: With overflow checks enabled, we verify here that the value is >= 0
> + #[cfg(CONFIG_RUST_OVERFLOW_CHECKS)]
> + assert!(res >= 0);

Same here?

> +
> + Self {
> + inner: res,
> + _c: PhantomData,
> + }
> + }
> +}
> +
> /// A span of time.
> ///
> /// This struct represents a span of time, with its value stored as nanoseconds.
> --
> 2.50.0
>
>