rust-lang / rust-lang/rust-clippy
New lint: Unnecessary use of std::ptr::{copy,copy_nonoverlapping} with slices
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
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 onCopytypes can be replaced withdst.slice[j..j+n].copy_from_slice(src_slice[i..i+n]).
Moreover, ifTisn'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_nonoverlappingcase)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No source file, test, or entry point is named. Start by reviewing how existing Clippy lints detect unsafe std::ptr::copy and copy_nonoverlapping patterns, then determine how the proposed slice replacements should be validated for Copy types, overlap, and ranges. Done means the lint reliably identifies the described cases and has coverage for its suggested replacements.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100