tl;dr: I propose to rewrite, for example, swap_with_slice from this current version (source)
// Before (minimized)
pub const fn swap_with_slice(&mut self, other: &mut [T]) {
unsafe {
ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
}
}
to lift self.len() to the front as follows:
// After (minimized)
pub const fn swap_with_slice(&mut self, other: &mut [T]) {
let len = self.len();
unsafe {
ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), len);
}
}
The same idea applies to the implementation of reverse and copy_from_slice.
Are there any downsides to such a rewrite?
Motivation
I'm working on formally verifying slice functions in core using Creusot (see also the Verify Rust std challenge).
Part of the approach is to annotate functions with "ghost code" to enable formal reasoning using our tool Creusot with no impact to run-time. The goal being to verify fragments of core, there is an automated "erasure check" that if you remove this ghost code, the remaining code must match the original code in core. This check works for most functions, except the three in the title.
In the swap_with_slice example above, the method as_mut_ptr returns a raw pointer, and we extend its result with some "ghost data" that lets us record what the pointer is pointing to. Unfortunately for us, this "ghost data" carries the same lifetime as the input borrow, whereas previously as_mut_ptr only returned a raw pointer so there were no lifetimes in the result. Because of this, self is no longer available to call self.len().
Hence our current solution is to rewrite this function to get self.len() first, and I'm wondering if it would make sense to upstream this single change to core, instead of extending our "erasure check" with an ad hoc rule for this case. (Our verified version of swap_with_slice for the curious.)
Indeed, even outside of formal verification, one could argue that self.as_mut_ptr() "morally borrows" from self, so calling self.len() while the raw pointer self.as_mut_ptr() is still in use is kinda smelly.
I'm curious to hear people's thoughts on this.