3 #![allow(clippy::stable_sort_primitive)]
8 fn unnecessary_sort_by() {
9 fn id(x: isize) -> isize {
13 let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
17 vec.sort_by_key(|a| (a + 5).abs());
18 vec.sort_unstable_by_key(|a| id(-a));
20 vec.sort_by(|a, b| b.cmp(a)); // not linted to avoid suggesting `Reverse(b)` which would borrow
21 vec.sort_by_key(|b| Reverse((b + 5).abs()));
22 vec.sort_unstable_by_key(|b| Reverse(id(-b)));
23 // Negative examples (shouldn't be changed)
25 vec.sort_by(|a, b| (b - a).cmp(&(a - b)));
26 vec.sort_by(|_, b| b.cmp(&5));
27 vec.sort_by(|_, b| b.cmp(c));
28 vec.sort_unstable_by(|a, _| a.cmp(c));
30 // Vectors of references are fine as long as the resulting key does not borrow
31 let mut vec: Vec<&&&isize> = vec![&&&3, &&&6, &&&1, &&&2, &&&5];
32 vec.sort_by_key(|a| (***a).abs());
33 vec.sort_unstable_by_key(|a| (***a).abs());
34 // `Reverse(b)` would borrow in the following cases, don't lint
35 vec.sort_by(|a, b| b.cmp(a));
36 vec.sort_unstable_by(|a, b| b.cmp(a));
38 // No warning if element does not implement `Ord`
39 let mut vec: Vec<Ref<usize>> = Vec::new();
40 vec.sort_unstable_by(|a, b| a.cmp(b));
43 // Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
45 #[derive(Clone, Copy)]
48 #[derive(PartialOrd, Ord, PartialEq, Eq)]
49 struct Wrapper<'a>(&'a usize);
52 fn name(&self) -> &usize {
56 fn wrapped(&self) -> Wrapper<'_> {
62 let mut args: Vec<Test> = vec![];
65 args.sort_by(|a, b| a.name().cmp(b.name()));
66 args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
67 args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
68 args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
70 args.sort_by(|a, b| b.name().cmp(a.name()));
71 args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
72 args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
73 args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
77 // The closure parameter is not dereferenced anymore, so non-Copy types can be linted
83 // Return an owned type so that we don't hit the fix for 5754
84 fn name(&self) -> String {
90 let mut args: Vec<Test> = vec![];
93 args.sort_by_key(|a| a.name());
94 args.sort_unstable_by_key(|a| a.name());
96 args.sort_by_key(|b| Reverse(b.name()));
97 args.sort_unstable_by_key(|b| Reverse(b.name()));
102 unnecessary_sort_by();