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