[PATCH v4 4/7] rust: time: Add Instant::from_nanos()

Lyude Paul posted 7 patches 9 months, 2 weeks ago
There is a newer version of this series
[PATCH v4 4/7] rust: time: Add Instant::from_nanos()
Posted by Lyude Paul 9 months, 2 weeks ago
For implementing Rust bindings which can return a point in time.

Signed-off-by: Lyude Paul <lyude@redhat.com>

---
V4:
* Turn from_nanos() into an unsafe function in order to ensure that we
  uphold the invariants of Instant

Signed-off-by: Lyude Paul <lyude@redhat.com>
---
 rust/kernel/time.rs | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index 8d6aa88724ad8..6dcb65ed954db 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -83,6 +83,21 @@ pub fn elapsed(&self) -> Delta {
     pub(crate) fn as_nanos(self) -> i64 {
         self.inner
     }
+
+    /// Create an `Instant` from a time duration specified in nano seconds.
+    ///
+    /// # Safety
+    ///
+    /// The caller promises that `nanos` is in the range from 0 to `KTIME_MAX`.
+    #[expect(unused)]
+    #[inline]
+    pub(crate) unsafe fn from_nanos(nanos: i64) -> Self {
+        // INVARIANT: Our safety contract ensures that `nanos` is in the range from 0 to
+        // `KTIME_MAX`.
+        Self {
+            inner: nanos as bindings::ktime_t,
+        }
+    }
 }
 
 impl core::ops::Sub for Instant {
-- 
2.48.1