Skip to contentSkip to conversation

rust: types: Add `try_from_foreign()` method

PATCH Superseded Obei Sideg 1 participant 1 message Jan 28, 2024 1 message not in the archive Rust

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): [email protected]

Obei Sideg

author
#1 lore raw

PATCH v4 1/1 rust: types: Add `try_from_foreign()` method

Currently ForeignOwnable::from_foreign() only works for non-null pointers for the existing impls (e.g. Box, Arc). It may create a few duplicate code like:

```rust
// `p` is a maybe null pointer
if p.is_null() {
  None
} else {
  unsafe { Some(Self::from_foreign(ptr)) }
}
```

Adding a try_from_foreign() method that will return null if ptr is null, otherwsie return from_foreign(ptr).

---
 rust/kernel/types.rs | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
rust/kernel/types.rs +17 -0
index fdb778e65d79..04a356ec3534 100644
@@ -46,6 +46,23 @@ pub trait ForeignOwnable: Sized {
     /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
     /// this object must have been dropped.
     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self;
+
+    /// Tries to convert a foreign-owned object back to a Rust-owned one.
+    ///
+    /// A convenience wrapper over [`from_foreign`] that returns [`None`] if `ptr` is null.
+    ///
+    /// # Safety
+    ///
+    /// `ptr` must either be null or satisfy the safety requirements for [`from_foreign`].
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
+        if ptr.is_null() {
+            None
+        } else {
+            // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
+            // call to [`into_foreign`].
+            unsafe { Some(Self::from_foreign(ptr)) }
+        }
+    }
 }
 
 impl<T: 'static> ForeignOwnable for Box<T> {
Signature · 1 line
2.39.2