Skip to contentSkip to conversation

rust: types: Add `try_from_foreign()` method

PATCH In review Obei Sideg 5 participants 6 messages Jan 22, 2024 – Jan 23, 2024 1 message not in the archive Rust

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 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 {
Some(unsafe { T::from_foreign(p) })
}
``

Link Rust-for-Linux/linux#1059
Cc Alice Ryhl <[email protected]>
Cc Matt Gilbride <[email protected]>
Cc Miguel Ojeda <[email protected]>
---
 rust/kernel/types.rs | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
rust/kernel/types.rs +20 -0
index fdb778e65d79..946067cd9c00 100644
@@ -46,6 +46,18 @@ 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.
+    ///
+    /// Like [`from_foreign`], but returns [`None`] if `ptr` is null.
+    ///
+    /// # Safety
+    ///
+    /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
+    /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
+    /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
+    /// this object must have been dropped.
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self>;
 }
 
 impl<T: 'static> ForeignOwnable for Box<T> {
@@ -68,6 +80,14 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
         // call to `Self::into_foreign`.
         unsafe { Box::from_raw(ptr as _) }
     }
+
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
+        if ptr.is_null() {
+            None
+        } else {
+            Some(Self::from_foreign(ptr))
+        }
+    }
 }
 
 impl ForeignOwnable for () {
Signature · 1 line
2.39.2
#2 lore raw
Quoted 29 lines · Obei Sideg

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 {
   Some(unsafe { T::from_foreign(p) })
}

``

Link Rust-for-Linux/linux#1059
Cc Alice Ryhl <[email protected]>
Cc Matt Gilbride <[email protected]>
Cc Miguel Ojeda <[email protected]>

---
[...]

rust/kernel/types.rs +1 -0
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self>;
  }
 
  impl<T: 'static> ForeignOwnable for Box<T> {
@@ -68,6 +80,14 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
          // call to `Self::into_foreign`.
          unsafe { Box::from_raw(ptr as _) }

rust/kernel/types.rs unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { · line 90

Quoted 10 lines
rust/kernel/types.rs +8 -0
      }
+
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
+        if ptr.is_null() {
+            None
+        } else {
+            Some(Self::from_foreign(ptr))
+        }
+    }
[...]

Shouldn't have Box::try_from_foreign been the default implementation of ForeignOwnable::try_from_foreign?

reviewer Reviewed-by on v1 1/1
#3 lore raw
In reply to Obei Sideg
Quoted 5 lines · Obei Sideg

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:

Minor nit: commit messages are wrapped to 72 characters, looks like this is 50.

Quoted 10 lines

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

Link Rust-for-Linux/linux#1059

You should link the issue
(https://github.com/Rust-for-Linux/linux/issues/1057) instead of or in addition to the PR.

Quoted 5 lines
Cc Alice Ryhl <[email protected]>
Cc Matt Gilbride <[email protected]>
Cc Miguel Ojeda <[email protected]>

Optional docs update below, in either case you may add:

Quoted 9 lines
---
 rust/kernel/types.rs | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
rust/kernel/types.rs +0 -0
index fdb778e65d79..946067cd9c00 100644

rust/kernel/types.rs pub trait ForeignOwnable: Sized { · line 52

Quoted 7 lines
rust/kernel/types.rs +4 -0
@@ -46,6 +46,18 @@ 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.
+    ///
+    /// Like [`from_foreign`], but returns [`None`] if `ptr` is null.

Maybe

A convenience wrapper over [from_foreign] that returns [None]
if ptr is null.

Just to be clear that this introduces no additional functionality.

Quoted 30 lines
rust/kernel/types.rs +15 -1
+    /// # Safety
+    ///
+    /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
+    /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
+    /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
+    /// this object must have been dropped.
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self>;
 }
 
 impl<T: 'static> ForeignOwnable for Box<T> {
@@ -68,6 +80,14 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
         // call to `Self::into_foreign`.
         unsafe { Box::from_raw(ptr as _) }
     }
+
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
+        if ptr.is_null() {
+            None
+        } else {
+            Some(Self::from_foreign(ptr))
+        }
+    }
 }
 
 impl ForeignOwnable for () {
--

2.39.2

reviewer
#4 lore raw
Quoted 5 lines · Trevor Gross
Quoted 3 lines · Obei Sideg

[...]

Quoted 8 lines
Quoted 4 lines
Cc Alice Ryhl <[email protected]>
Cc Matt Gilbride <[email protected]>
Cc Miguel Ojeda <[email protected]>

Optional docs update below, in either case you may add:

The others have a good point, please resend with a default implementation on ForeignOwnable and I will re-review.

#5 lore raw
In reply to Trevor Gross
Quoted 8 lines · Trevor Gross
Quoted 5 lines · Obei Sideg

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:

Minor nit: commit messages are wrapped to 72 characters, looks like this is 50.

It is actually 75 characters max:

"The body of the explanation, line wrapped at 75 columns, which will be copied to the permanent changelog to describe this patch."

See https://www.kernel.org/doc/html/latest/process/submitting-patches.html#the-canonical-patch-format

BR, Jarkko

#6 lore raw
In reply to Obei Sideg

rust/kernel/types.rs pub trait ForeignOwnable: Sized { · line 60

Quoted 11 lines · Obei Sideg
rust/kernel/types.rs +11 -0
+    /// Tries to convert a foreign-owned object back to a Rust-owned one.
+    ///
+    /// Like [`from_foreign`], but returns [`None`] if `ptr` is null.
+    ///
+    /// # Safety
+    ///
+    /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
+    /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
+    /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
+    /// this object must have been dropped.
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self>;

The safety comment should probably say "If ptr is not null, then ...".

rust/kernel/types.rs unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { · line 90

Quoted 13 lines
  impl<T: 'static> ForeignOwnable for Box<T> {
rust/kernel/types.rs +8 -0
@@ -68,6 +80,14 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
          // call to `Self::into_foreign`.
          unsafe { Box::from_raw(ptr as _) }
      }
+
+    unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
+        if ptr.is_null() {
+            None
+        } else {
+            Some(Self::from_foreign(ptr))
+        }
+    }

I would just add a default implementation in the trait declaration. That way, you can avoid adding the method to every implementation.

Alice