Skip to content

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

Open
@nicoonoclaste

Description

@nicoonoclaste

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-correctnessLint: Belongs in the correctness lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions