]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/tests/ui/unnecessary_sort_by.fixed
Auto merge of #74576 - myfreeweb:freebsd-sanitizers, r=oli-obk
[rust.git] / src / tools / clippy / tests / ui / unnecessary_sort_by.fixed
1 // run-rustfix
2
3 #![allow(clippy::stable_sort_primitive)]
4
5 use std::cmp::Reverse;
6
7 fn unnecessary_sort_by() {
8     fn id(x: isize) -> isize {
9         x
10     }
11
12     let mut vec: Vec<isize> = vec![3, 6, 1, 2, 5];
13     // Forward examples
14     vec.sort();
15     vec.sort_unstable();
16     vec.sort_by_key(|&a| (a + 5).abs());
17     vec.sort_unstable_by_key(|&a| id(-a));
18     // Reverse examples
19     vec.sort_by_key(|&b| Reverse(b));
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)
23     let c = &7;
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));
28 }
29
30 // Should not be linted to avoid hitting https://github.com/rust-lang/rust/issues/34162
31 mod issue_5754 {
32     struct Test(String);
33
34     #[derive(PartialOrd, Ord, PartialEq, Eq)]
35     struct Wrapper<'a>(&'a str);
36
37     impl Test {
38         fn name(&self) -> &str {
39             &self.0
40         }
41
42         fn wrapped(&self) -> Wrapper<'_> {
43             Wrapper(&self.0)
44         }
45     }
46
47     pub fn test() {
48         let mut args: Vec<Test> = vec![];
49
50         // Forward
51         args.sort_by(|a, b| a.name().cmp(b.name()));
52         args.sort_by(|a, b| a.wrapped().cmp(&b.wrapped()));
53         args.sort_unstable_by(|a, b| a.name().cmp(b.name()));
54         args.sort_unstable_by(|a, b| a.wrapped().cmp(&b.wrapped()));
55         // Reverse
56         args.sort_by(|a, b| b.name().cmp(a.name()));
57         args.sort_by(|a, b| b.wrapped().cmp(&a.wrapped()));
58         args.sort_unstable_by(|a, b| b.name().cmp(a.name()));
59         args.sort_unstable_by(|a, b| b.wrapped().cmp(&a.wrapped()));
60     }
61 }
62
63 fn main() {
64     unnecessary_sort_by();
65     issue_5754::test();
66 }