Transmuting a single &mut self to two &mut self's through &self
I was working on a task which required to modify two elements of an array at once. At first I though about using split_at_mut with some clever indexing, however I was not pleased with the mental complexity. Hence I wanted to implement a function which ensured that the two given indexes were different and did some unsafe code to take two mutable references. I my head this seems safe because taking two distinct indexes from a slice, should always point to non-overlapping data (this is also true for ZSTs, right?). Hence I created the following trait and implementation:
/// Extension trait to allow a container to return a mutable pointer to several
/// non-overlapping items
pub trait SliceIndexMutExt<T, K> {
/// Gets the value of two non-overlapping indexes as mutable pointers
///
/// # Panics
///
/// If either index is out of bounds this function will panic.
fn get_nonoverlapping_mut(&mut self, a: K, b: K) -> (&mut T, &mut T);
}
impl<T> SliceIndexMutExt<T, usize> for [T] {
fn get_nonoverlapping_mut(&mut self, a: usize, b: usize) -> (&mut T, &mut T) {
assert!(a != b, "Values are overlapping");
// As long as a != b this will always be safe
unsafe {
(
&mut *(&self[a] as *const T as *mut T),
&mut *(&self[b] as *const T as *mut T),
)
}
// Safe version
//
// if a < b {
// let (lower, upper) = self.split_at_mut(a + 1);
// (&mut lower[a], &mut upper[b - a - 1])
// } else {
// let (lower, upper) = self.split_at_mut(b + 1);
// (&mut lower[b], &mut upper[a - b - 1])
// }
}
}
However after reading a bit in the nomicon I realized that I am not special, and that the casting from &self to &mut self is UB:
Transmuting an & to &mut is UB. Transmuting an & to &mut is always UB. No you can't do it. No you're not special.
I have probably been lucky, but I have not experienced any weird behaviour in my tests or in my program. I realized that this is the nature of UB, that I might be lucky, but I was still wondering if this is truly UB? Technically the function has &mut self when the it's called, and further it ensures that the indexes are not equal.
Posted Jan 28, 2019, 9:46 PM UTC · edited
The formal semantics of what alias-based UB is is not totally nailed down yet (ongoing discussion here, one detailed proposal here). IIRC one of the proposals was to strictly make it UB if there are ever two values in scope that can both be used to mutably access the same memory location if at least one of them is a
&mut, which your implementation violates because while constructing the second element of the tuple you have access toself[a]through both the first element of the tuple andself. But the standard library's implementation ofsplit_at_mutdoes the exact same thing. I suggest using thesplit_at_mutversion so that if the final UB model decides that that pattern is unacceptable, your code will be automatically updated to avoid it when the standard library fixes its implementation.Thank you for the links and the good advice regarding using the
split_at_mut-solution instead is clever.I needed this exact same thing for some code I wrote a little while ago too. My implementation:
Your implementation is a bit more clever regarding bounds, as it is smart to rather split on the highest index to prevent my
b - a - 1calculation.These sound like a perfect use for UnsafeCell as a way of completely avoiding undefined behavior to duplicate a mutable reference. Would you happen to know a reason why not?
I don't see how you would encorporate
UnsafeCellinto this example. If you could give a concrete example of using unsafe cell without changing the signature of the function, that would be great.Actually, scratch that.
*mut TimplementsCopy.offsetone, then usefrom_raw_parts_muton both.