Description
During a Secure Code WG audit, I ran into the following unsafe
code patterns, which can always be replaced with safe code with essentially no drawback or overhead:
-
std::ptr::copy{,_nonoverlapping}(&src_slice[i] as *const T, &mut dst_slice[j] as *mut T, n)
All non-UB uses onCopy
types can be replaced withdst.slice[j..j+n].copy_from_slice(src_slice[i..i+n])
.
Moreover, ifT
isn'tCopy
, this is UB and should be replaced withdst.slice[j..j+n].clone_from_slice(src_slice[i..i+n])
-
std::ptr::copy{,_nonoverlapping}(&s[i] as *const T, &mut s[j] as *mut T, n)
Same idea, non-UB uses can be replaced withs.copy_within(i..i+n, j)
.
If the ranges are non-overlapping, it might be faster to use slice::split_at_mut and copy_from_slice (resulting in a call tostd::ptr::copy_nonoverlapping
), but that might be too much static analysis to ask from Clippy (though it can be safely assumed in thecopy_nonoverlapping
case)