Re: [PATCH v2 5/8] rust: time: Add Instant::from_nanos()

From: FUJITA Tomonori
Date: Wed Apr 16 2025 - 05:11:21 EST


On Tue, 15 Apr 2025 15:48:26 -0400
Lyude Paul <lyude@xxxxxxxxxx> wrote:

> For implementing Rust bindings which can return a point in time.
>
> Signed-off-by: Lyude Paul <lyude@xxxxxxxxxx>
> ---
> rust/kernel/time.rs | 8 ++++++++
> 1 file changed, 8 insertions(+)
>
> diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
> index 8d6aa88724ad8..545963140f180 100644
> --- a/rust/kernel/time.rs
> +++ b/rust/kernel/time.rs
> @@ -83,6 +83,14 @@ pub fn elapsed(&self) -> Delta {
> pub(crate) fn as_nanos(self) -> i64 {
> self.inner
> }
> +
> + #[expect(unused)]
> + #[inline]
> + pub(crate) fn from_nanos(nanos: i64) -> Self {
> + Self {
> + inner: nanos as bindings::ktime_t,
> + }
> + }
> }

We need to guarantee the following Invariants.

/// A specific point in time.
///
/// # Invariants
///
/// The `inner` value is in the range from 0 to `KTIME_MAX`.
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct Instant {
inner: bindings::ktime_t,
}

Otherwise, The method of the Sub trait may cause an overflow

By the way, what are some use cases for creating an Instant from
driver's input?