rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Replace `if s.split('.').count() == 1` with `if !s.contains('.')`

Open Logarithmus opened this issue 2 years ago • 5 comments

What it does

I've found this "ingenious" snippet in a big Rust codebase, and Clippy didn't catch it.

Lint Name

str-split-count-1

Example

if url.split('|').count() == 1 {

}

Could be written as:

if !url.contains('.') {

}

Logarithmus avatar Jul 12 '22 10:07 Logarithmus

But this not equal code? In first example you want exactly one separator, where in second you want >= 1.

klensy avatar Jul 12 '22 11:07 klensy

@klensy sorry, I forgot ! before the second snippet. Now it should do the same thing perhaps? And the first example wants not one separator, but exactly one part of a string, which is possible iff no separators found at all.

Logarithmus avatar Jul 12 '22 11:07 Logarithmus

but exactly one part of a string, which is possible iff no separators found at all.

Ah, yes.

klensy avatar Jul 12 '22 12:07 klensy

In the example, split('|') should be split('.'), I think(?).

smoelius avatar Jul 12 '22 14:07 smoelius

Can this be generalized to if the result of std::iter::Iterator::count() is compared to 1 or 0, it can *always* be replaced by *some* variant of std::iter::Iterator::any()?

lukaslueg avatar Aug 10 '22 17:08 lukaslueg