Skip to contentSkip to conversation

rust: time: implement `Debug` for `Delta`

PATCH In review Andreas Hindborg 3 participants 5 messages Nov 26

Subsystems (2)
lore
Share & tools
lore

Andreas Hindborg

author maintainer
#0 lore raw

PATCH v3 1/1 rust: time: implement `Debug` for `Delta`

Implement the Debug trait for Delta so that a span of time can be printed by a formatter.

The span is printed as a count of the time unit it is stored in, suffixed with that unit, and with each group of three digits separated by an underscore the way Rust integer literals are written. A span of 12345 nanoseconds is printed as 12_345 ns.

Debug is implemented rather than Display, because Delta has no single obvious format and the other kernel types that carry a unit, Hertz, MicroVolt and MicroWatt, implement Debug only. Callers that need a specific format should use Delta::as_nanos and print the result themselves.

---
Changes in v3:
- Implement Debug rather than Display, as Delta has no single
obvious format and the other kernel types that carry a unit
implement Debug only (Tomonori).
- Implement the formatting for every time unit rather than for
nanoseconds only, via a new TimeUnit::SUFFIX.
- Separate each group of three digits with an underscore (Miguel).
- Separate the value and the unit with a space.
- Add KUnit tests for the formatting.
- Link to v2: https://msgid.link/[email protected]

Changes in v2:
- Rebased on v7.4-rc1.
- Suffix the formatted value with ns (Alice, Gary, Miguel).
- Write the value directly rather than via write_fmt and fmt! (Alice).
- Document the format with a rustdoc example.
- Drop the rnull user, which will call Delta::as_nanos instead (Gary).
- Link to v1: https://msgid.link/[email protected]

---
 rust/kernel/time.rs | 134 +++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 133 insertions(+), 1 deletion(-)
rust/kernel/time.rs +133 -1
index b6a2aab12a50..8b38d4c70c87 100644
@@ -309,6 +309,12 @@ pub trait TimeUnit: private::Sealed {
 
     /// The zero value of [`Self::Repr`].
     const ZERO: Self::Repr;
+
+    /// The suffix that denotes this unit when a [`Delta`] is formatted.
+    const SUFFIX: &'static str;
+
+    /// Widens `repr` to an [`i64`].
+    fn repr_to_i64(repr: Self::Repr) -> i64;
 }
 
 /// A time unit of nanoseconds.
@@ -321,6 +327,12 @@ pub enum Nsec {}
 impl TimeUnit for Nsec {
     type Repr = i64;
     const ZERO: Self::Repr = 0;
+    const SUFFIX: &'static str = "ns";
+
+    #[inline]
+    fn repr_to_i64(repr: Self::Repr) -> i64 {
+        repr
+    }
 }
 
 /// A time unit of jiffies.
@@ -333,6 +345,14 @@ pub enum Jiffy {}
 impl TimeUnit for Jiffy {
     type Repr = isize;
     const ZERO: Self::Repr = 0;
+    const SUFFIX: &'static str = "jiffies";
+
+    #[inline]
+    fn repr_to_i64(repr: Self::Repr) -> i64 {
+        // CAST: `isize` is 32 or 64 bits wide on the architectures the kernel
+        // supports, so widening to `i64` preserves the value.
+        repr as i64
+    }
 }
 
 /// A span of time.
@@ -341,7 +361,7 @@ impl TimeUnit for Jiffy {
 /// [`TimeUnit`]); its value has type `U::Repr`. `U` defaults to [`Nsec`], so a
 /// plain [`Delta`] is a span in nanoseconds. The value can be negative, zero, or
 /// positive.
-#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Debug)]
+#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
 pub struct Delta<U: TimeUnit = Nsec> {
     value: U::Repr,
 }
@@ -669,10 +689,122 @@ pub fn rem_nanos(self, dividend: i32) -> Self {
     }
 }
 
+impl<U: TimeUnit> kernel::fmt::Debug for Delta<U> {
+    /// Formats the span as a number of time units, followed by the unit.
+    ///
+    /// The value and the unit are separated by a space, and each group of three
+    /// digits is separated by an underscore, the way Rust integer literals are
+    /// written.
+    ///
+    /// ```
+    /// # use kernel::{prelude::fmt, str::CString, time::Delta};
+    /// let delta = Delta::from_micros(5);
+    /// let formatted = CString::try_from_fmt(fmt!("{delta:?}"))?;
+    /// assert_eq!(formatted.to_bytes(), b"5_000 ns");
+    ///
+    /// let negative = Delta::from_millis(-2);
+    /// let formatted = CString::try_from_fmt(fmt!("{negative:?}"))?;
+    /// assert_eq!(formatted.to_bytes(), b"-2_000_000 ns");
+    ///
+    /// let jiffies = Delta::from_jiffies(1234);
+    /// let formatted = CString::try_from_fmt(fmt!("{jiffies:?}"))?;
+    /// assert_eq!(formatted.to_bytes(), b"1_234 jiffies");
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
+    fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {
+        let value = U::repr_to_i64(self.value);
+
+        if value < 0 {
+            f.write_str("-")?;
+        }
+
+        // `unsigned_abs` is used because the magnitude of `i64::MIN` is not
+        // representable as an `i64`.
+        let mut magnitude = value.unsigned_abs();
+
+        // Split the magnitude into groups of three digits, least significant
+        // group first. A `u64` holds at most 20 digits, so 7 groups suffice.
+        //
+        // Dividing by the constant keeps the compiler from emitting a check for
+        // a division by zero with a potential panic.
+        let mut groups = [0u64; 7];
+        let mut used = 0;
+
+        for group in groups.iter_mut() {
+            *group = magnitude % 1000;
+            magnitude /= 1000;
+            used += 1;
+
+            if magnitude == 0 {
+                break;
+            }
+        }
+
+        let mut groups = groups.into_iter().take(used).rev();
+
+        // The leading group holds the most significant digits of the value, so
+        // it is the only one that is not zero padded.
+        if let Some(leading) = groups.next() {
+            write!(f, "{}", leading)?;
+        }
+
+        for group in groups {
+            write!(f, "_{:03}", group)?;
+        }
+
+        write!(f, " {}", U::SUFFIX)
+    }
+}
+
 #[cfg(CONFIG_RUST_TIME_KUNIT_TEST)]
 #[macros::kunit_tests(rust_kernel_time)]
 mod tests {
     use super::*;
+    use crate::{prelude::fmt, str::CString};
+
+    /// Formats `delta` with its [`kernel::fmt::Debug`] implementation.
+    fn debug_fmt<U: TimeUnit>(delta: Delta<U>) -> Result<CString, crate::error::Error> {
+        CString::try_from_fmt(fmt!("{delta:?}"))
+    }
+
+    #[test]
+    fn delta_debug_separates_digit_groups() -> Result<(), crate::error::Error> {
+        // A value below one thousand is printed without a separator.
+        assert_eq!(debug_fmt(Delta::from_nanos(999))?.to_bytes(), b"999 ns");
+
+        // Groups that do not lead the value are zero padded.
+        assert_eq!(debug_fmt(Delta::from_nanos(1000))?.to_bytes(), b"1_000 ns");
+        assert_eq!(
+            debug_fmt(Delta::from_nanos(1_000_007))?.to_bytes(),
+            b"1_000_007 ns"
+        );
+
+        // Zero has a single group.
+        assert_eq!(debug_fmt(Delta::<Nsec>::ZERO)?.to_bytes(), b"0 ns");
+
+        // The extremes of the representation are printed in full. The magnitude
+        // of `i64::MIN` does not fit an `i64`, which makes it the interesting
+        // one.
+        assert_eq!(
+            debug_fmt(Delta::from_nanos(i64::MAX))?.to_bytes(),
+            b"9_223_372_036_854_775_807 ns"
+        );
+        assert_eq!(
+            debug_fmt(Delta::from_nanos(i64::MIN))?.to_bytes(),
+            b"-9_223_372_036_854_775_808 ns"
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn delta_debug_uses_the_unit_suffix() -> Result<(), crate::error::Error> {
+        assert_eq!(debug_fmt(Delta::from_nanos(1))?.to_bytes(), b"1 ns");
+        assert_eq!(debug_fmt(Delta::from_jiffies(1))?.to_bytes(), b"1 jiffies");
+        assert_eq!(debug_fmt(Delta::<Jiffy>::ZERO)?.to_bytes(), b"0 jiffies");
+
+        Ok(())
+    }
 
     #[test]
     fn to_jiffies_timeout_converts() {

---
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
change-id: 20260215-time-delta-display-d702e7788d2d

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
#1 lore raw
Quoted 12 lines · On Thu, 26 Nov 2026 11:51:14 +0100 Andreas Hindborg <[email protected]>…
rust/kernel/time.rs +12 -0
+    fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {
+        let value = U::repr_to_i64(self.value);
+
+        if value < 0 {
+            f.write_str("-")?;
+        }
+
+        // `unsigned_abs` is used because the magnitude of `i64::MIN` is not
+        // representable as an `i64`.
+        let mut magnitude = value.unsigned_abs();
+
+        // Split the magnitude into groups of three digits, least significant

rust/kernel/time.rs pub fn rem_nanos(self, dividend: i32) -> Self { · line 735

Quoted 10 lines
rust/kernel/time.rs +10 -0
+        // group first. A `u64` holds at most 20 digits, so 7 groups suffice.
+        //
+        // Dividing by the constant keeps the compiler from emitting a check for
+        // a division by zero with a potential panic.
+        let mut groups = [0u64; 7];
+        let mut used = 0;
+
+        for group in groups.iter_mut() {
+            *group = magnitude % 1000;
+            magnitude /= 1000;

Code that uses this Debug impl fails to build on 32-bit ARM, for example the doctests:

ld.lld-20: error: undefined symbol: __aeabi_uldivmod

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

referenced by doctests_kernel_generated.ea22ff07120af58c-cgu.0
rust/doctests_kernel_generated.o:(<kernel::fmt::Adapter<&kernel::time::Delta<kernel::time::Jiffy>> as core::fmt::Debug>::fmt) in archive vmlinux.a

div64_u64() in my series [1] should work here:

    let quotient = div64_u64(magnitude, 1000);
    *group = magnitude - quotient * 1000;
    magnitude = quotient;

If you prefer, we could also add div_u64_rem() to the math module.

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

author maintainer
#2 lore raw
Quoted 33 lines · FUJITA Tomonori
Quoted 12 lines · On Thu, 26 Nov 2026 11:51:14 +0100 Andreas Hindborg <[email protected]>…
rust/kernel/time.rs +12 -0
+    fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {
+        let value = U::repr_to_i64(self.value);
+
+        if value < 0 {
+            f.write_str("-")?;
+        }
+
+        // `unsigned_abs` is used because the magnitude of `i64::MIN` is not
+        // representable as an `i64`.
+        let mut magnitude = value.unsigned_abs();
+
+        // Split the magnitude into groups of three digits, least significant

rust/kernel/time.rs pub fn rem_nanos(self, dividend: i32) -> Self { · line 735

Quoted 10 lines
rust/kernel/time.rs +10 -0
+        // group first. A `u64` holds at most 20 digits, so 7 groups suffice.
+        //
+        // Dividing by the constant keeps the compiler from emitting a check for
+        // a division by zero with a potential panic.
+        let mut groups = [0u64; 7];
+        let mut used = 0;
+
+        for group in groups.iter_mut() {
+            *group = magnitude % 1000;
+            magnitude /= 1000;

Code that uses this Debug impl fails to build on 32-bit ARM, for example the doctests:

ld.lld-20: error: undefined symbol: __aeabi_uldivmod

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

referenced by doctests_kernel_generated.ea22ff07120af58c-cgu.0
rust/doctests_kernel_generated.o:(<kernel::fmt::Adapter<&kernel::time::Delta<kernel::time::Jiffy>> as core::fmt::Debug>::fmt) in archive vmlinux.a

Quoted 7 lines

div64_u64() in my series [1] should work here:

    let quotient = div64_u64(magnitude, 1000);
    *group = magnitude - quotient * 1000;
    magnitude = quotient;

If you prefer, we could also add div_u64_rem() to the math module.

Ah, thanks. I'll re-spin on top of that series, adding the remainder function.

Best regards,
Andreas Hindborg

reviewer
#3 lore raw
In reply to Andreas Hindborg
Quoted 8 lines · Andreas Hindborg

Implement the Debug trait for Delta so that a span of time can be printed by a formatter.

The span is printed as a count of the time unit it is stored in, suffixed with that unit, and with each group of three digits separated by an underscore the way Rust integer literals are written. A span of 12345 nanoseconds is printed as 12_345 ns.

Quoted 5 lines

Debug is implemented rather than Display, because Delta has no single obvious format and the other kernel types that carry a unit, Hertz, MicroVolt and MicroWatt, implement Debug only. Callers that need a specific format should use Delta::as_nanos and print the result themselves.

Thanks for addressing the earlier feedback! Aside from the 32-bit division issue that Tomonori already pointed out, this looks good to me.

rust/kernel/time.rs pub enum Jiffy {} · line 355

Quoted 6 lines
rust/kernel/time.rs +6 -0
+    #[inline]
+    fn repr_to_i64(repr: Self::Repr) -> i64 {
+        // CAST: `isize` is 32 or 64 bits wide on the architectures the kernel
+        // supports, so widening to `i64` preserves the value.
+        repr as i64
+    }

Maybe we could add impl FromSafeCast<isize> for i64 to kernel::num::casts and use i64::from_safe_cast(repr) here?

Quoted 1 line

+ let mut groups = [0u64; 7];

Minor nit: since each group is < 1000, this could be [0u16; 7] instead of [0u64; 7].

Alice

author maintainer
#4 lore raw
Quoted 25 lines · Alice Ryhl
Quoted 8 lines · Andreas Hindborg

Implement the Debug trait for Delta so that a span of time can be printed by a formatter.

The span is printed as a count of the time unit it is stored in, suffixed with that unit, and with each group of three digits separated by an underscore the way Rust integer literals are written. A span of 12345 nanoseconds is printed as 12_345 ns.

Quoted 5 lines

Debug is implemented rather than Display, because Delta has no single obvious format and the other kernel types that carry a unit, Hertz, MicroVolt and MicroWatt, implement Debug only. Callers that need a specific format should use Delta::as_nanos and print the result themselves.

Thanks for addressing the earlier feedback! Aside from the 32-bit division issue that Tomonori already pointed out, this looks good to me.

rust/kernel/time.rs pub enum Jiffy {} · line 355

Quoted 6 lines
rust/kernel/time.rs +6 -0
+    #[inline]
+    fn repr_to_i64(repr: Self::Repr) -> i64 {
+        // CAST: `isize` is 32 or 64 bits wide on the architectures the kernel
+        // supports, so widening to `i64` preserves the value.
+        repr as i64
+    }
Quoted 2 lines

Maybe we could add impl FromSafeCast<isize> for i64 to kernel::num::casts and use i64::from_safe_cast(repr) here?

I can try to add that.

Quoted 5 lines
Quoted 2 lines

+ let mut groups = [0u64; 7];

Minor nit: since each group is < 1000, this could be [0u16; 7] instead of [0u64; 7].

I chose the u64 so I would not have to narrow from 64 to 16. I valued the cleaner code over the wasted bits.

Best regards,
Andreas Hindborg