From 2935dd642e897172905c843e355542f60138b3f2 Mon Sep 17 00:00:00 2001 From: Sebastiano Vigna Date: Sun, 17 Nov 2024 08:47:52 +0000 Subject: [PATCH] from_mut is unsafe to mark the possibility of UB --- src/algo/llp/mod.rs | 2 +- src/utils/sync_slice.rs | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/algo/llp/mod.rs b/src/algo/llp/mod.rs index d7908c3b..b579e3de 100644 --- a/src/algo/llp/mod.rs +++ b/src/algo/llp/mod.rs @@ -408,7 +408,7 @@ fn combine(result: &mut [usize], labels: &[usize], temp_perm: &mut [usize]) -> R } pub fn invert_permutation(perm: &[usize], inv_perm: &mut [usize]) { - let sync_slice = SyncSlice::from_mut(inv_perm); + let sync_slice = unsafe { SyncSlice::from_mut(inv_perm) }; perm.par_iter().enumerate().for_each(|(i, &x)| { sync_slice.set(x, i); }); diff --git a/src/utils/sync_slice.rs b/src/utils/sync_slice.rs index 5660ea29..fde1d7e0 100644 --- a/src/utils/sync_slice.rs +++ b/src/utils/sync_slice.rs @@ -42,8 +42,17 @@ unsafe impl<'a, T: Send> Sync for SyncSlice<'a, T> {} impl<'a, T> SyncSlice<'a, T> { /// Creates a new synchronized slice from a mutable reference. + /// + /// # Safety + /// + /// It is the caller's responsibility to ensure that no data + /// races occur. + /// + /// # Undefined Behavior + /// + /// Data races will cause undefined behaviour. #[inline(always)] - pub fn from_mut(slice: &'a mut [T]) -> Self { + pub unsafe fn from_mut(slice: &'a mut [T]) -> Self { Self(Cell::from_mut(slice).as_slice_of_cells()) } } @@ -152,11 +161,12 @@ impl<'a, T> SyncSlice<'a, T> { /// Extension trait providing a [synchronized view](SyncSlice) of a slice via /// the [`as_sync_slice`](SyncSliceExt::as_sync_slice) method. pub trait SyncSliceExt<'a, T: Copy> { - fn as_sync_slice(&'a mut self) -> SyncSlice<'a, T>; + /// Invokes [`SyncSlice::from_mut`] on the slice. + unsafe fn as_sync_slice(&'a mut self) -> SyncSlice<'a, T>; } impl<'a, T: Copy> SyncSliceExt<'a, T> for [T] { - fn as_sync_slice(&'a mut self) -> SyncSlice<'a, T> { + unsafe fn as_sync_slice(&'a mut self) -> SyncSlice<'a, T> { SyncSlice::from_mut(self) } }