3 #![allow(clippy::stable_sort_primitive)]
7 fn unnecessary_sort_by() {
8 fn id(x: isize) -> isize {
12 let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
16 vec.sort_by_key(|a| (a + 5).abs());
17 vec.sort_unstable_by_key(|a| id(-a));
19 vec.sort_by(|a, b| b.cmp(a)); // not linted to avoid suggesting `Reverse(b)` which would borrow
20 vec.sort_by_key(|b| Reverse((b + 5).abs()));
21 vec.sort_unstable_by_key(|b| Reverse(id(-b)));
22 // Negative examples (shouldn't be changed)
24 vec.sort_by(|a, b| (b - a).cmp(&(a - b)));
25 vec.sort_by(|_, b| b.cmp(&5));
26 vec.sort_by(|_, b| b.cmp(c));
27 vec.sort_unstable_by(|a, _| a.cmp(c));
29 // Vectors of references are fine as long as the resulting key does not borrow
30 let mut vec: Vec<&&&isize> = vec![&&&3, &&&6, &&&1, &&&2, &&&5];
31 vec.sort_by_key(|a| (***a).abs());
32 vec.sort_unstable_by_key(|a| (***a).abs());
33 // `Reverse(b)` would borrow in the following cases, don't lint
34 vec.sort_by(|a, b| b.cmp(a));
35 vec.sort_unstable_by(|a, b| b.cmp(a));
38 // Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
40 #[derive(Clone, Copy)]
43 #[derive(PartialOrd, Ord, PartialEq, Eq)]
44 struct Wrapper<'a>(&'a usize);
47 fn name(&self) -> &usize {
51 fn wrapped(&self) -> Wrapper<'_> {
57 let mut args: Vec<Test> = vec![];
60 args.sort_by(|a, b| a.name().cmp(b.name()));
61 args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
62 args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
63 args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
65 args.sort_by(|a, b| b.name().cmp(a.name()));
66 args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
67 args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
68 args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
72 // The closure parameter is not dereferenced anymore, so non-Copy types can be linted
78 // Return an owned type so that we don't hit the fix for 5754
79 fn name(&self) -> String {
85 let mut args: Vec<Test> = vec![];
88 args.sort_by_key(|a| a.name());
89 args.sort_unstable_by_key(|a| a.name());
91 args.sort_by_key(|b| Reverse(b.name()));
92 args.sort_unstable_by_key(|b| Reverse(b.name()));
97 unnecessary_sort_by();