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| std::cmp::Reverse((b + 5).abs()));
21 vec.sort_unstable_by_key(|b| std::cmp::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));
37 // No warning if element does not implement `Ord`
38 let mut vec: Vec<Ref<usize>> = Vec::new();
39 vec.sort_unstable_by(|a, b| a.cmp(b));
42 // Do not suggest returning a reference to the closure parameter of `Vec::sort_by_key`
44 #[derive(Clone, Copy)]
47 #[derive(PartialOrd, Ord, PartialEq, Eq)]
48 struct Wrapper<'a>(&'a usize);
51 fn name(&self) -> &usize {
55 fn wrapped(&self) -> Wrapper<'_> {
61 let mut args: Vec<Test> = vec![];
64 args.sort_by(|a, b| a.name().cmp(b.name()));
65 args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
66 args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
67 args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
69 args.sort_by(|a, b| b.name().cmp(a.name()));
70 args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
71 args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
72 args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
76 // The closure parameter is not dereferenced anymore, so non-Copy types can be linted
81 // Return an owned type so that we don't hit the fix for 5754
82 fn name(&self) -> String {
88 let mut args: Vec<Test> = vec![];
91 args.sort_by_key(|a| a.name());
92 args.sort_unstable_by_key(|a| a.name());
94 args.sort_by_key(|b| std::cmp::Reverse(b.name()));
95 args.sort_unstable_by_key(|b| std::cmp::Reverse(b.name()));
100 unnecessary_sort_by();