mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Andreas Hindborg <a.hindborg@kernel.org>
To: "FUJITA Tomonori" <fujita.tomonori@gmail.com>,
	"Frederic Weisbecker" <frederic@kernel.org>,
	"Lyude Paul" <lyude@redhat.com>,
	"Thomas Gleixner" <tglx@kernel.org>,
	"Anna-Maria Behnsen" <anna-maria@linutronix.de>,
	"John Stultz" <jstultz@google.com>,
	"Stephen Boyd" <sboyd@kernel.org>,
	"Miguel Ojeda" <ojeda@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"Boqun Feng" <boqun@kernel.org>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
	 Andreas Hindborg <a.hindborg@kernel.org>
Subject: [PATCH v3] rust: time: implement `Debug` for `Delta`
Date: Thu, 26 Nov 2026 11:51:14 +0100	[thread overview]
Message-ID: <20261126-time-delta-display-v3-1-aeeecc72f3a8@kernel.org> (raw)

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>



             reply	other threads:[~2026-11-26 10:51 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-26 10:51 Andreas Hindborg [this message]
2026-11-26 11:25 ` FUJITA Tomonori
2026-11-26 12:01   ` Andreas Hindborg

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261126-time-delta-display-v3-1-aeeecc72f3a8@kernel.org \
    --to=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=anna-maria@linutronix.de \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=frederic@kernel.org \
    --cc=fujita.tomonori@gmail.com \
    --cc=gary@garyguo.net \
    --cc=jstultz@google.com \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=lyude@redhat.com \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=sboyd@kernel.org \
    --cc=tamird@kernel.org \
    --cc=tglx@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=work@onurozkan.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
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®