[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20240324223339.971934-3-boqun.feng@gmail.com>
Date: Sun, 24 Mar 2024 15:33:36 -0700
From: Boqun Feng <boqun.feng@...il.com>
To: rust-for-linux@...r.kernel.org,
linux-kernel@...r.kernel.org,
Thomas Gleixner <tglx@...utronix.de>
Cc: Alice Ryhl <aliceryhl@...gle.com>,
Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>,
Wedson Almeida Filho <wedsonaf@...il.com>,
Boqun Feng <boqun.feng@...il.com>,
Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
benno.lossin@...ton.me,
Andreas Hindborg <a.hindborg@...sung.com>,
John Stultz <jstultz@...gle.com>,
Stephen Boyd <sboyd@...nel.org>,
Valentin Obst <kernel@...entinobst.de>
Subject: [PATCH 2/5] rust: time: Introduce Duration type
From: Alice Ryhl <aliceryhl@...gle.com>
Introduce a type representing time duration. Define our own type instead
of using `core::time::Duration` because in kernel C code, an i64
(ktime_t) is used for representing time durations, an i64 backed
duration type is more efficient when interacting with time APIs in C.
Signed-off-by: Alice Ryhl <aliceryhl@...gle.com>
[boqun: Rename `Ktime` to `Duration`, and make it a type of durations]
Signed-off-by: Boqun Feng <boqun.feng@...il.com>
---
rust/kernel/time.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index bbb666e64dd7..b238b3a4e899 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -7,6 +7,9 @@
//!
//! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h).
+/// The number of nanoseconds per millisecond.
+pub const NSEC_PER_MSEC: i64 = bindings::NSEC_PER_MSEC as i64;
+
/// The time unit of Linux kernel. One jiffy equals (1/HZ) second.
pub type Jiffies = core::ffi::c_ulong;
@@ -20,3 +23,44 @@ pub fn msecs_to_jiffies(msecs: Msecs) -> Jiffies {
// matter what the argument is.
unsafe { bindings::__msecs_to_jiffies(msecs) }
}
+
+/// A time duration.
+///
+/// # Examples
+///
+/// ```
+/// let one_second = kernel::time::Duration::new(1000_000_000);
+///
+/// // 1 second is 1000 milliseconds.
+/// assert_eq!(one_second.to_ms(), 1000);
+/// ```
+#[repr(transparent)]
+#[derive(Copy, Clone, Debug)]
+pub struct Duration {
+ inner: i64,
+}
+
+impl Duration {
+ /// Creates a new duration of `ns` nanoseconds.
+ pub const fn new(ns: i64) -> Self {
+ Self { inner: ns }
+ }
+
+ /// Divides the number of nanoseconds by a compile-time constant.
+ #[inline]
+ fn divns_constant<const DIV: i64>(self) -> i64 {
+ self.to_ns() / DIV
+ }
+
+ /// Returns the number of milliseconds.
+ #[inline]
+ pub fn to_ms(self) -> i64 {
+ self.divns_constant::<NSEC_PER_MSEC>()
+ }
+
+ /// Returns the number of nanoseconds.
+ #[inline]
+ pub fn to_ns(self) -> i64 {
+ self.inner
+ }
+}
--
2.44.0
Powered by blists - more mailing lists