]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
rust: arc: use `NonNull::new_unchecked`
authorTamir Duberstein <tamird@gmail.com>
Wed, 20 Nov 2024 11:46:00 +0000 (06:46 -0500)
committerMiguel Ojeda <ojeda@kernel.org>
Mon, 13 Jan 2025 22:45:30 +0000 (23:45 +0100)
There is no need to check (and panic on violations of) the safety
requirements on `ForeignOwnable` functions. Avoiding the check is
consistent with the implementation of `ForeignOwnable` for `Box`.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20241120-borrow-mut-v6-1-80dbadd00951@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
rust/kernel/sync/arc.rs

index 25d2185df4cb1f1ddee37223a79d6d93f971e25b..2f3156b6aacf5581eac54a53008670662d6c6413 100644 (file)
@@ -349,9 +349,9 @@ impl<T: 'static> ForeignOwnable for Arc<T> {
     }
 
     unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> ArcBorrow<'a, T> {
-        // By the safety requirement of this function, we know that `ptr` came from
-        // a previous call to `Arc::into_foreign`.
-        let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
+        // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
+        // call to `Self::into_foreign`.
+        let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner<T>) };
 
         // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
         // for the lifetime of the returned value.
@@ -359,10 +359,14 @@ impl<T: 'static> ForeignOwnable for Arc<T> {
     }
 
     unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self {
+        // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
+        // call to `Self::into_foreign`.
+        let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner<T>) };
+
         // SAFETY: By the safety requirement of this function, we know that `ptr` came from
         // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
         // holds a reference count increment that is transferrable to us.
-        unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) }
+        unsafe { Self::from_inner(inner) }
     }
 }