3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
6 use syntax::ast::{Name, UintTy};
7 use crate::utils::{contains_name, get_pat_name, match_type, paths, single_segment_path, snippet, span_lint_and_sugg,
10 /// **What it does:** Checks for naive byte counts
12 /// **Why is this bad?** The [`bytecount`](https://crates.io/crates/bytecount)
13 /// crate has methods to count your bytes faster, especially for large slices.
15 /// **Known problems:** If you have predominantly small slices, the
16 /// `bytecount::count(..)` method may actually be slower. However, if you can
17 /// ensure that less than 2³²-1 matches arise, the `naive_count_32(..)` can be
18 /// faster in those cases.
23 /// &my_data.filter(|&x| x == 0u8).count() // use bytecount::count instead
25 declare_clippy_lint! {
28 "use of naive `<slice>.filter(|&x| x == y).count()` to count byte values"
31 #[derive(Copy, Clone)]
34 impl LintPass for ByteCount {
35 fn get_lints(&self) -> LintArray {
36 lint_array!(NAIVE_BYTECOUNT)
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ByteCount {
41 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr) {
43 if let ExprKind::MethodCall(ref count, _, ref count_args) = expr.node;
44 if count.ident.name == "count";
45 if count_args.len() == 1;
46 if let ExprKind::MethodCall(ref filter, _, ref filter_args) = count_args[0].node;
47 if filter.ident.name == "filter";
48 if filter_args.len() == 2;
49 if let ExprKind::Closure(_, _, body_id, _, _) = filter_args[1].node;
51 let body = cx.tcx.hir.body(body_id);
53 if body.arguments.len() == 1;
54 if let Some(argname) = get_pat_name(&body.arguments[0].pat);
55 if let ExprKind::Binary(ref op, ref l, ref r) = body.value.node;
56 if op.node == BinOpKind::Eq;
58 walk_ptrs_ty(cx.tables.expr_ty(&filter_args[0])),
61 let needle = match get_path_name(l) {
62 Some(name) if check_arg(name, argname, r) => r,
63 _ => match get_path_name(r) {
64 Some(name) if check_arg(name, argname, l) => l,
68 if ty::TyUint(UintTy::U8) != walk_ptrs_ty(cx.tables.expr_ty(needle)).sty {
71 let haystack = if let ExprKind::MethodCall(ref path, _, ref args) =
73 let p = path.ident.name;
74 if (p == "iter" || p == "iter_mut") && args.len() == 1 {
82 span_lint_and_sugg(cx,
85 "You appear to be counting bytes the naive way",
86 "Consider using the bytecount crate",
87 format!("bytecount::count({}, {})",
88 snippet(cx, haystack.span, ".."),
89 snippet(cx, needle.span, "..")));
97 fn check_arg(name: Name, arg: Name, needle: &Expr) -> bool {
98 name == arg && !contains_name(name, needle)
101 fn get_path_name(expr: &Expr) -> Option<Name> {
103 ExprKind::Box(ref e) | ExprKind::AddrOf(_, ref e) | ExprKind::Unary(UnOp::UnDeref, ref e) => get_path_name(e),
104 ExprKind::Block(ref b, _) => if b.stmts.is_empty() {
105 b.expr.as_ref().and_then(|p| get_path_name(p))
109 ExprKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),