rust-lang / rust-lang/rust-clippy

New lint: Unnecessary use of std::ptr::{copy,copy_nonoverlapping} with slices

Open
#4,862 5 comments 8 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint E-medium L-correctness
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 on Copy types can be replaced with dst.slice[j..j+n].copy_from_slice(src_slice[i..i+n]).
    Moreover, if T isn't Copy, this is UB and should be replaced with dst.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 with s.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 to std::ptr::copy_nonoverlapping), but that might be too much static analysis to ask from Clippy (though it can be safely assumed in the copy_nonoverlapping case)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.