1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::ty::match_type;
4 use clippy_utils::visitors::is_local_used;
5 use clippy_utils::{path_to_local_id, paths, peel_blocks, peel_ref_operators, strip_pat_refs};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind, PatKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty::{self, UintTy};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
16 /// Checks for naive byte counts
18 /// ### Why is this bad?
19 /// The [`bytecount`](https://crates.io/crates/bytecount)
20 /// crate has methods to count your bytes faster, especially for large slices.
22 /// ### Known problems
23 /// If you have predominantly small slices, the
24 /// `bytecount::count(..)` method may actually be slower. However, if you can
25 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
26 /// faster in those cases.
30 /// # let vec = vec![1_u8];
31 /// let count = vec.iter().filter(|x| **x == 0u8).count();
36 /// # let vec = vec![1_u8];
37 /// let count = bytecount::count(&vec, 0u8);
39 #[clippy::version = "pre 1.29.0"]
42 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
45 declare_lint_pass!(ByteCount => [NAIVE_BYTECOUNT]);
47 impl<'tcx> LateLintPass<'tcx> for ByteCount {
48 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
50 if let ExprKind::MethodCall(count, [count_recv], _) = expr.kind;
51 if count.ident.name == sym::count;
52 if let ExprKind::MethodCall(filter, [filter_recv, filter_arg], _) = count_recv.kind;
53 if filter.ident.name == sym!(filter);
54 if let ExprKind::Closure(_, _, body_id, _, _) = filter_arg.kind;
55 let body = cx.tcx.hir().body(body_id);
56 if let [param] = body.params;
57 if let PatKind::Binding(_, arg_id, _, _) = strip_pat_refs(param.pat).kind;
58 if let ExprKind::Binary(ref op, l, r) = body.value.kind;
59 if op.node == BinOpKind::Eq;
61 cx.typeck_results().expr_ty(filter_recv).peel_refs(),
63 let operand_is_arg = |expr| {
64 let expr = peel_ref_operators(cx, peel_blocks(expr));
65 path_to_local_id(expr, arg_id)
67 let needle = if operand_is_arg(l) {
69 } else if operand_is_arg(r) {
74 if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(needle).peel_refs().kind();
75 if !is_local_used(cx, needle, arg_id);
77 let haystack = if let ExprKind::MethodCall(path, args, _) =
79 let p = path.ident.name;
80 if (p == sym::iter || p == sym!(iter_mut)) && args.len() == 1 {
88 let mut applicability = Applicability::MaybeIncorrect;
93 "you appear to be counting bytes the naive way",
94 "consider using the bytecount crate",
95 format!("bytecount::count({}, {})",
96 snippet_with_applicability(cx, haystack.span, "..", &mut applicability),
97 snippet_with_applicability(cx, needle.span, "..", &mut applicability)),