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