* [PATCH v3] rust: time: implement `Debug` for `Delta`
@ 2026-11-26 10:51 Andreas Hindborg
2026-11-26 11:25 ` FUJITA Tomonori
2026-11-26 12:59 ` Alice Ryhl
0 siblings, 2 replies; 5+ messages in thread
From: Andreas Hindborg @ 2026-11-26 10:51 UTC (permalink / raw)
To: FUJITA Tomonori, Frederic Weisbecker, Lyude Paul,
Thomas Gleixner, Anna-Maria Behnsen, John Stultz, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Alice Ryhl, Trevor Gross, Danilo Krummrich, Boqun Feng,
Daniel Almeida, Tamir Duberstein, Alexandre Courbot,
Onur Özkan, Boqun Feng
Cc: rust-for-linux, linux-kernel, 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`.
`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.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
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/20261103-time-delta-display-v2-1-b01b1fe9ff9f@kernel.org
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/20260215-time-delta-display-v1-1-bdd2d6e98ebf@kernel.org
---
rust/kernel/time.rs | 134 +++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 133 insertions(+), 1 deletion(-)
diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index b6a2aab12a50..8b38d4c70c87 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -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,
--
Andreas Hindborg <a.hindborg@kernel.org>
^ permalink raw reply [flat|nested] 5+ messages in thread
* Re: [PATCH v3] rust: time: implement `Debug` for `Delta`
2026-11-26 10:51 [PATCH v3] rust: time: implement `Debug` for `Delta` Andreas Hindborg
@ 2026-11-26 11:25 ` FUJITA Tomonori
2026-11-26 12:01 ` Andreas Hindborg
2026-11-26 12:59 ` Alice Ryhl
1 sibling, 1 reply; 5+ messages in thread
From: FUJITA Tomonori @ 2026-11-26 11:25 UTC (permalink / raw)
To: a.hindborg
Cc: fujita.tomonori, frederic, lyude, tglx, anna-maria, jstultz,
sboyd, ojeda, gary, bjorn3_gh, lossin, aliceryhl, tmgross, dakr,
boqun, daniel.almeida, tamird, acourbot, work, rust-for-linux,
linux-kernel
On Thu, 26 Nov 2026 11:51:14 +0100
Andreas Hindborg <a.hindborg@kernel.org> wrote:
> + 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;
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
>>> 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/20261118224826.2491684-1-tomo@flapping.org/
^ permalink raw reply [flat|nested] 5+ messages in thread
* Re: [PATCH v3] rust: time: implement `Debug` for `Delta`
2026-11-26 11:25 ` FUJITA Tomonori
@ 2026-11-26 12:01 ` Andreas Hindborg
0 siblings, 0 replies; 5+ messages in thread
From: Andreas Hindborg @ 2026-11-26 12:01 UTC (permalink / raw)
To: FUJITA Tomonori
Cc: fujita.tomonori, frederic, lyude, tglx, anna-maria, jstultz,
sboyd, ojeda, gary, bjorn3_gh, lossin, aliceryhl, tmgross, dakr,
boqun, daniel.almeida, tamird, acourbot, work, rust-for-linux,
linux-kernel
"FUJITA Tomonori" <tomo@flapping.org> writes:
> On Thu, 26 Nov 2026 11:51:14 +0100
> Andreas Hindborg <a.hindborg@kernel.org> wrote:
>
>> + 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;
>
> 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
>>>> 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.
Ah, thanks. I'll re-spin on top of that series, adding the remainder function.
Best regards,
Andreas Hindborg
^ permalink raw reply [flat|nested] 5+ messages in thread
* Re: [PATCH v3] rust: time: implement `Debug` for `Delta`
2026-11-26 10:51 [PATCH v3] rust: time: implement `Debug` for `Delta` Andreas Hindborg
2026-11-26 11:25 ` FUJITA Tomonori
@ 2026-11-26 12:59 ` Alice Ryhl
2026-11-26 13:31 ` Andreas Hindborg
1 sibling, 1 reply; 5+ messages in thread
From: Alice Ryhl @ 2026-11-26 12:59 UTC (permalink / raw)
To: Andreas Hindborg
Cc: Alice Ryhl, FUJITA Tomonori, Frederic Weisbecker, Lyude Paul,
Thomas Gleixner, Anna-Maria Behnsen, John Stultz, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Trevor Gross, Danilo Krummrich, Boqun Feng, Daniel Almeida,
Tamir Duberstein, Alexandre Courbot, Onur Özkan,
rust-for-linux, linux-kernel
On Thu, Nov 26, 2026 at 11:51:14AM +0100, Andreas Hindborg wrote:
> 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.
Thanks for addressing the earlier feedback! Aside from the 32-bit division
issue that Tomonori already pointed out, this looks good to me.
> + #[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?
> + let mut groups = [0u64; 7];
Minor nit: since each group is `< 1000`, this could be `[0u16; 7]` instead
of `[0u64; 7]`.
Alice
^ permalink raw reply [flat|nested] 5+ messages in thread
* Re: [PATCH v3] rust: time: implement `Debug` for `Delta`
2026-11-26 12:59 ` Alice Ryhl
@ 2026-11-26 13:31 ` Andreas Hindborg
0 siblings, 0 replies; 5+ messages in thread
From: Andreas Hindborg @ 2026-11-26 13:31 UTC (permalink / raw)
To: Alice Ryhl
Cc: Alice Ryhl, FUJITA Tomonori, Frederic Weisbecker, Lyude Paul,
Thomas Gleixner, Anna-Maria Behnsen, John Stultz, Stephen Boyd,
Miguel Ojeda, Gary Guo, Björn Roy Baron, Benno Lossin,
Trevor Gross, Danilo Krummrich, Boqun Feng, Daniel Almeida,
Tamir Duberstein, Alexandre Courbot, Onur Özkan,
rust-for-linux, linux-kernel
Alice Ryhl <aliceryhl@google.com> writes:
> On Thu, Nov 26, 2026 at 11:51:14AM +0100, Andreas Hindborg wrote:
>> 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.
>
> Thanks for addressing the earlier feedback! Aside from the 32-bit division
> issue that Tomonori already pointed out, this looks good to me.
>
>> + #[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?
I can try to add that.
>
>> + 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
^ permalink raw reply [flat|nested] 5+ messages in thread
end of thread, other threads:[~2026-11-26 13:31 UTC | newest]
Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-26 10:51 [PATCH v3] rust: time: implement `Debug` for `Delta` Andreas Hindborg
2026-11-26 11:25 ` FUJITA Tomonori
2026-11-26 12:01 ` Andreas Hindborg
2026-11-26 12:59 ` Alice Ryhl
2026-11-26 13:31 ` Andreas Hindborg
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®