Skip to content

Commit c6340da

Browse files
tamirdojeda
authored andcommitted
rust: arc: use NonNull::new_unchecked
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 <[email protected]> Reviewed-by: Andreas Hindborg <[email protected]> Signed-off-by: Tamir Duberstein <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 47cb6bf commit c6340da

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

rust/kernel/sync/arc.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -349,20 +349,24 @@ impl<T: 'static> ForeignOwnable for Arc<T> {
349349
}
350350

351351
unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> ArcBorrow<'a, T> {
352-
// By the safety requirement of this function, we know that `ptr` came from
353-
// a previous call to `Arc::into_foreign`.
354-
let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
352+
// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
353+
// call to `Self::into_foreign`.
354+
let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner<T>) };
355355

356356
// SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive
357357
// for the lifetime of the returned value.
358358
unsafe { ArcBorrow::new(inner) }
359359
}
360360

361361
unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self {
362+
// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
363+
// call to `Self::into_foreign`.
364+
let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner<T>) };
365+
362366
// SAFETY: By the safety requirement of this function, we know that `ptr` came from
363367
// a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
364368
// holds a reference count increment that is transferrable to us.
365-
unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) }
369+
unsafe { Self::from_inner(inner) }
366370
}
367371
}
368372

0 commit comments

Comments
 (0)