enhance needless_collect

Updates `needless_collect` to lint for collecting into a method or
function argument thats taking an `IntoIterator` (for example `extend`).
Every `Iterator` trivially implements `IntoIterator` and colleting it
only causes an unnecessary allocation.
This commit is contained in:
Icxolu 2023-05-13 11:47:05 +02:00
parent a167973e81
commit 84f89f30eb
4 changed files with 115 additions and 3 deletions

View file

@ -62,4 +62,16 @@ fn main() {
let _ = sample.iter().next().is_none();
let _ = sample.iter().any(|x| x == &0);
#[allow(clippy::double_parens)]
{
Vec::<u8>::new().extend((0..10));
foo((0..10));
bar((0..10).collect::<Vec<_>>(), (0..10));
baz((0..10), (), ('a'..='z'))
}
}
fn foo(_: impl IntoIterator<Item = usize>) {}
fn bar<I: IntoIterator<Item = usize>>(_: Vec<usize>, _: I) {}
fn baz<I: IntoIterator<Item = usize>>(_: I, _: (), _: impl IntoIterator<Item = char>) {}

View file

@ -62,4 +62,16 @@ fn main() {
let _ = sample.iter().collect::<VecWrapper<_>>().is_empty();
let _ = sample.iter().collect::<VecWrapper<_>>().contains(&&0);
#[allow(clippy::double_parens)]
{
Vec::<u8>::new().extend((0..10).collect::<Vec<_>>());
foo((0..10).collect::<Vec<_>>());
bar((0..10).collect::<Vec<_>>(), (0..10).collect::<Vec<_>>());
baz((0..10), (), ('a'..='z').collect::<Vec<_>>())
}
}
fn foo(_: impl IntoIterator<Item = usize>) {}
fn bar<I: IntoIterator<Item = usize>>(_: Vec<usize>, _: I) {}
fn baz<I: IntoIterator<Item = usize>>(_: I, _: (), _: impl IntoIterator<Item = char>) {}

View file

@ -90,5 +90,29 @@ error: avoid using `collect()` when not needed
LL | let _ = sample.iter().collect::<VecWrapper<_>>().contains(&&0);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `any(|x| x == &0)`
error: aborting due to 15 previous errors
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:68:40
|
LL | Vec::<u8>::new().extend((0..10).collect::<Vec<_>>());
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:69:20
|
LL | foo((0..10).collect::<Vec<_>>());
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:70:49
|
LL | bar((0..10).collect::<Vec<_>>(), (0..10).collect::<Vec<_>>());
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call
error: avoid using `collect()` when not needed
--> $DIR/needless_collect.rs:71:37
|
LL | baz((0..10), (), ('a'..='z').collect::<Vec<_>>())
| ^^^^^^^^^^^^^^^^^^^^ help: remove this call
error: aborting due to 19 previous errors