Skip to content

needless_pass_by_ref_mut triggers on mutable raw pointer #12905

@Thomasdezeeuw

Description

@Thomasdezeeuw

Summary

When using raw points (*mut T) needless_pass_by_ref_mut seems to trigger, where it would be unsound to only accept a read only reference.

Lint Name

needless_pass_by_ref_mut

Reproducer

The actual code is here: github.com/Thomasdezeeuw/a10/blob/c3183d21af1f38858abd5178dd964a5b605a6681/src/io/read_buf.rs#L470-L480.

The follow is a smaller reproduction.

pub struct ReadBuf {
    len: usize,
    owned: Option<NonNull<[u8]>>,
}

impl ReadBuf {
    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
        if let Some(ptr) = self.owned {
            let unused_len = self.len - ptr.len();
            let data = unsafe { ptr.as_ptr().cast::<u8>().add(ptr.len()) };
            unsafe { slice::from_raw_parts_mut(data.cast(), unused_len) }
        } else {
            &mut []
        }
    }
}

I saw this happen:

error: this argument is a mutable reference, but not used mutably
   --> src/io/read_buf.rs:470:31
    |
470 |     pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
    |                               ^^^^^^^^^ help: consider changing to: `&self`
    |
    = warning: changing this function will impact semver compatibility
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
    = note: `-D clippy::needless-pass-by-ref-mut` implied by `-D clippy::nursery`
    = help: to override `-D clippy::nursery` add `#[allow(clippy::needless_pass_by_ref_mut)]`

I expected to see this happen:

No warning as it would be unsound to change the method to only accept a read only reference and then return a mutable reference.

Version

rustc 1.80.0-nightly (867900499 2024-05-23)
binary: rustc
commit-hash: 8679004993f08807289911d9f400f4ac4391d2bc
commit-date: 2024-05-23
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.6

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveL-nurseryLint: Currently in the nursery group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions