Skip to content

Commit

Permalink
from_mut is unsafe to mark the possibility of UB
Browse files Browse the repository at this point in the history
  • Loading branch information
vigna committed Nov 17, 2024
1 parent bf62ccb commit 2935dd6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/algo/llp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
16 changes: 13 additions & 3 deletions src/utils/sync_slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
Expand Down Expand Up @@ -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)
}
}

0 comments on commit 2935dd6

Please sign in to comment.