From 48f99151c5c4d451b402c10a98a8c32defb9bcab Mon Sep 17 00:00:00 2001 From: AurelienFT Date: Fri, 7 Jun 2024 21:42:27 +0200 Subject: [PATCH] check_manual_pattern_char_comparison: avoid indexing and increase readability --- clippy_lints/src/string_patterns.rs | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/clippy_lints/src/string_patterns.rs b/clippy_lints/src/string_patterns.rs index 5d9b70f4230e..69fb97188a7f 100644 --- a/clippy_lints/src/string_patterns.rs +++ b/clippy_lints/src/string_patterns.rs @@ -1,4 +1,3 @@ -use std::cmp::Ordering; use std::ops::ControlFlow; use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; @@ -18,7 +17,7 @@ use rustc_span::{sym, Span}; declare_clippy_lint! { /// ### What it does - /// Checks for manual char comparison in string patterns + /// Checks for manual `char` comparison in string patterns /// /// ### Why is this bad? /// This can be written more concisely using a `char` or an array of `char`. @@ -26,11 +25,11 @@ declare_clippy_lint! { /// /// ### Example /// ```no_run - /// "Hello World !".trim_end_matches(|c: char| c == '.' || c == ',' || c == '!' || c == '?'); + /// "Hello World!".trim_end_matches(|c| c == '.' || c == ',' || c == '!' || c == '?'); /// ``` /// Use instead: /// ```no_run - /// "Hello World !".trim_end_matches(['.', ',', '!', '?']); + /// "Hello World!".trim_end_matches(['.', ',', '!', '?']); /// ``` #[clippy::version = "1.80.0"] pub MANUAL_PATTERN_CHAR_COMPARISON, @@ -124,10 +123,9 @@ fn get_char_span<'tcx>(cx: &'_ LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Optio } fn check_manual_pattern_char_comparison(cx: &LateContext<'_>, method_arg: &Expr<'_>) { - let applicability = Applicability::MachineApplicable; if let ExprKind::Closure(closure) = method_arg.kind && let body = cx.tcx.hir().body(closure.body) - && let PatKind::Binding(_, binding, ..) = body.params[0].pat.kind + && let Some(PatKind::Binding(_, binding, ..)) = body.params.first().map(|p| p.pat.kind) { let mut set_char_spans: Vec = Vec::new(); @@ -185,16 +183,15 @@ fn check_manual_pattern_char_comparison(cx: &LateContext<'_>, method_arg: &Expr< MANUAL_PATTERN_CHAR_COMPARISON, method_arg.span, "this manual char comparison can be written more succinctly", - |diag| match set_char_spans.len().cmp(&1) { - Ordering::Equal => { + |diag| { + if let [set_char_span] = set_char_spans[..] { diag.span_suggestion( method_arg.span, "consider using a `char`", - snippet(cx, set_char_spans[0], "c"), - applicability, + snippet(cx, set_char_span, "c"), + Applicability::MachineApplicable, ); - }, - Ordering::Greater => { + } else { diag.span_suggestion( method_arg.span, "consider using an array of `char`", @@ -202,10 +199,9 @@ fn check_manual_pattern_char_comparison(cx: &LateContext<'_>, method_arg: &Expr< "[{}]", set_char_spans.into_iter().map(|span| snippet(cx, span, "c")).join(", ") ), - applicability, + Applicability::MachineApplicable, ); - }, - Ordering::Less => {}, + } }, ); }