Description
What it does
When .ends_with()
is called on a String or &str, and the parameter looks like a file extension (regex \.([a-z0-9]{1,5})|([A-Z0-9]{1,5})
), inform the programmer that this code will not handle differently-cased filenames well - potentially a bug. Additionally, a correct replacement is suggested (see below).
Categories
- Kind:
clippy::pedantic
or perhapsclippy::correctness
What is the advantage of the recommended code over the original code
It handles file extensions correctly regardless of case. In Windows, this behavior is very much expected since the entire operating system has case-insensitive filenames. In Linux, filenames are usually case-sensitive, but I think even on Linux, it's standard behavior to recognize file extensions regardless of case.
Drawbacks
- The suggested improvement is harder to read than the naive case-sensitive version
- The line
.ends_with(".ext")
might not be a file extension check at all. It could mean something else for which case-sensitivity makes sense
Example
if !filename.ends_with(".abc") {
panic!("Please provide an ABC file");
}
Could be written as:
if filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case("abc")) != Some(true) {
panic!("Please provide an ABC file");
}
Or like this (nightly-only because of Path::eq_ignore_ascii_case
):
let filename = Path::new(filename);
if filename.extension().map(|ext| ext.eq_ignore_ascii_case("abc")) != Some(true) {
panic!("Please provide an ABC file");
}