Skip to content

Commit 5bc8184

Browse files
obeisojeda
authored andcommitted
rust: types: add try_from_foreign() method
Currently `ForeignOwnable::from_foreign()` only works for non-null pointers for the existing `impl`s (e.g. `Box`, `Arc`). In turn, this means callers may write code like: ```rust // `p` is a pointer that may be null. if p.is_null() { None } else { unsafe { Some(Self::from_foreign(ptr)) } } ``` Add a `try_from_foreign()` method to the trait with a default implementation that returns `None` if `ptr` is null, otherwise `Some(from_foreign(ptr))`, so that it can be used by callers instead. Link: #1057 Signed-off-by: Obei Sideg <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Trevor Gross <[email protected]> Link: https://lore.kernel.org/r/0100018d53f737f8-80c1fe97-0019-40d7-ab69-b1b192785cd7-000000@email.amazonses.com [ Fixed intra-doc links, improved `SAFETY` comment and reworded commit. ] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent e3c3d34 commit 5bc8184

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

rust/kernel/types.rs

+19
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,25 @@ pub trait ForeignOwnable: Sized {
4646
/// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
4747
/// this object must have been dropped.
4848
unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self;
49+
50+
/// Tries to convert a foreign-owned object back to a Rust-owned one.
51+
///
52+
/// A convenience wrapper over [`ForeignOwnable::from_foreign`] that returns [`None`] if `ptr`
53+
/// is null.
54+
///
55+
/// # Safety
56+
///
57+
/// `ptr` must either be null or satisfy the safety requirements for
58+
/// [`ForeignOwnable::from_foreign`].
59+
unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
60+
if ptr.is_null() {
61+
None
62+
} else {
63+
// SAFETY: Since `ptr` is not null here, then `ptr` satisfies the safety requirements
64+
// of `from_foreign` given the safety requirements of this function.
65+
unsafe { Some(Self::from_foreign(ptr)) }
66+
}
67+
}
4968
}
5069

5170
impl<T: 'static> ForeignOwnable for Box<T> {

0 commit comments

Comments
 (0)