rust: types: Add `try_from_foreign()` method
A message that is not in the archive (sent off-list or not yet received): [email protected]
PATCH v5 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 None if ptr is null, otherwsie return Some(from_foreign(ptr)).
Signed-off-by Obei Sideg <[email protected]>
Reviewed-by Alice Ryhl <[email protected]>
Signed-off-by Obei Sideg <[email protected]>
--- rust/kernel/types.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
rust/kernel/types.rs +17 -0
@@ -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