-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Open
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-suggestion-causes-bugIssue: The suggestion compiles but changes the code to behave in an unintended wayIssue: The suggestion compiles but changes the code to behave in an unintended waygood first issueThese issues are a good way to get started with ClippyThese issues are a good way to get started with Clippy
Description
Description
needless_range_loop currently suggests using take(n) when the iteration is not bounded by the vec's length. This is dangerous since it will silently truncate the iterated range which can very easily lead to data corruption. It may be fine to do so, but we don't have the necessary information to make that decision from clippy.
The following:
fn f() {
let n = 15;
let v = vec![1, 2];
for i in 0..n {
let _ = n;
let _ = v[i];
}
}The current suggestion is effectively:
fn f() {
let n = 15;
let v = vec![1, 2];
for (i, x) in v.iter().enumerate().take(n) {
let _ = n;
let _ = *x;
}
}It should be something that preserves the panic. e.g.:
fn f() {
let n = 15;
let v = vec![1, 2];
for (i, x) in v[..n].iter().enumerate() {
let _ = n;
let _ = *x;
}
}Note that this will move the panic to occur before iteration rather than on the iteration that goes out of bounds. This behaviour is likely to be fine, but it should be called out by the lint when making this suggestion.
Version
clippy 0.1.91 (f8297e351a 2025-10-28)
Additional Labels
No response
Metadata
Metadata
Assignees
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-suggestion-causes-bugIssue: The suggestion compiles but changes the code to behave in an unintended wayIssue: The suggestion compiles but changes the code to behave in an unintended waygood first issueThese issues are a good way to get started with ClippyThese issues are a good way to get started with Clippy