]> git.lizzy.rs Git - rust.git/blob - tests/ui/option_map_unwrap_or.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[rust.git] / tests / ui / option_map_unwrap_or.rs
1 // FIXME: Add "run-rustfix" once it's supported for multipart suggestions
2 // aux-build:option_helpers.rs
3
4 #![warn(clippy::option_map_unwrap_or, clippy::option_map_unwrap_or_else)]
5
6 #[macro_use]
7 extern crate option_helpers;
8
9 use std::collections::HashMap;
10
11 /// Checks implementation of the following lints:
12 /// * `OPTION_MAP_UNWRAP_OR`
13 /// * `OPTION_MAP_UNWRAP_OR_ELSE`
14 #[rustfmt::skip]
15 fn option_methods() {
16     let opt = Some(1);
17
18     // Check `OPTION_MAP_UNWRAP_OR`.
19     // Single line case.
20     let _ = opt.map(|x| x + 1)
21         // Should lint even though this call is on a separate line.
22         .unwrap_or(0);
23     // Multi-line cases.
24     let _ = opt.map(|x| {
25         x + 1
26     }
27     ).unwrap_or(0);
28     let _ = opt.map(|x| x + 1)
29         .unwrap_or({
30             0
31         });
32     // Single line `map(f).unwrap_or(None)` case.
33     let _ = opt.map(|x| Some(x + 1)).unwrap_or(None);
34     // Multi-line `map(f).unwrap_or(None)` cases.
35     let _ = opt.map(|x| {
36         Some(x + 1)
37     }
38     ).unwrap_or(None);
39     let _ = opt
40         .map(|x| Some(x + 1))
41         .unwrap_or(None);
42     // macro case
43     let _ = opt_map!(opt, |x| x + 1).unwrap_or(0); // should not lint
44
45     // Should not lint if not copyable
46     let id: String = "identifier".to_string();
47     let _ = Some("prefix").map(|p| format!("{}.{}", p, id)).unwrap_or(id);
48     // ...but DO lint if the `unwrap_or` argument is not used in the `map`
49     let id: String = "identifier".to_string();
50     let _ = Some("prefix").map(|p| format!("{}.", p)).unwrap_or(id);
51
52     // Check OPTION_MAP_UNWRAP_OR_ELSE
53     // single line case
54     let _ = opt.map(|x| x + 1)
55         // Should lint even though this call is on a separate line.
56         .unwrap_or_else(|| 0);
57     // Multi-line cases.
58     let _ = opt.map(|x| {
59         x + 1
60     }
61     ).unwrap_or_else(|| 0);
62     let _ = opt.map(|x| x + 1)
63         .unwrap_or_else(||
64             0
65         );
66     // Macro case.
67     // Should not lint.
68     let _ = opt_map!(opt, |x| x + 1).unwrap_or_else(|| 0);
69
70     // Issue #4144
71     {
72         let mut frequencies = HashMap::new();
73         let word = "foo";
74
75         frequencies
76             .get_mut(word)
77             .map(|count| {
78                 *count += 1;
79             })
80             .unwrap_or_else(|| {
81                 frequencies.insert(word.to_owned(), 1);
82             });
83     }
84 }
85
86 fn main() {
87     option_methods();
88 }