rust-lang / rust-lang/rust-clippy
needless_pass_by_ref_mut triggers on mutable raw pointer
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
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
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
Start with the reproducer in src/io/read_buf.rs and locate the implementation and tests for the needless_pass_by_ref_mut lint. Confirm the lint's behavior for a method returning a mutable slice from raw-pointer-backed data, then add a regression test showing that this case does not warn while genuine needless mutable references still do.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100