rust-lang / rust-lang/rust-clippy
Add lint for calling `VecDeque::swap` as it might panic
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
Triggers on use of possibly-panicking function VecDeque::swap when index is out of bounds, similar to existing lint clippy::indexing_slicing.
Categories (optional)
- Kind: restriction
Recommended code would not panic, swap would. For users trying to prevent all (or all non-std) panics, this would be useful.
For example:
- Do not use
.swap, instead uselet (a, b) = get_mut(0)?, get_mut(1)?; std::mem::swap(&a, &b);
Drawbacks
None.
Example
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::restriction)]
#![allow(clippy::missing_docs_in_private_items, clippy::blanket_clippy_restriction_lints)]
use std::collections::VecDeque;
fn main() {
let mut c: VecDeque<u8> = VecDeque::new();
c.push_back(0);
c.push_back(1);
let _ = c[0]; // clippy::indexing_slicing correctly detects possible panic
c.swap(0, 1); // Could cause panic; clippy ignores this line
// c.swap(1, 2); // Example swap panic
}
Could be written as:
// ...
// Honestly I don't know the right way to do this. I would expect something like this
// But you can't borrow c mutably more than once
let (a, b) = (c.get_mut(0)?, c.get_mut(1)?);
std::mem::swap(&a, &b);
// ...
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 by reviewing the existing clippy::indexing_slicing lint and how it handles potentially panicking operations. Use the VecDeque::swap examples in this issue to define the expected cases, and consider the suggested get_mut approach when checking the intended non-panicking alternative. Done means the lint identifies potentially out-of-bounds VecDeque::swap calls without incorrectly flagging safe usage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools, tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100