]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/tests/ui/explicit_deref_methods.rs
Rollup merge of #99474 - aDotInTheVoid:rustdoc-json-noinline-test-cleanup, r=CraftSpider
[rust.git] / src / tools / clippy / tests / ui / explicit_deref_methods.rs
1 // run-rustfix
2
3 #![allow(
4     unused_variables,
5     clippy::clone_double_ref,
6     clippy::needless_borrow,
7     clippy::borrow_deref_ref,
8     clippy::explicit_auto_deref
9 )]
10 #![warn(clippy::explicit_deref_methods)]
11
12 use std::ops::{Deref, DerefMut};
13
14 fn concat(deref_str: &str) -> String {
15     format!("{}bar", deref_str)
16 }
17
18 fn just_return(deref_str: &str) -> &str {
19     deref_str
20 }
21
22 struct CustomVec(Vec<u8>);
23 impl Deref for CustomVec {
24     type Target = Vec<u8>;
25
26     fn deref(&self) -> &Vec<u8> {
27         &self.0
28     }
29 }
30
31 fn main() {
32     let a: &mut String = &mut String::from("foo");
33
34     // these should require linting
35
36     let b: &str = a.deref();
37
38     let b: &mut str = a.deref_mut();
39
40     // both derefs should get linted here
41     let b: String = format!("{}, {}", a.deref(), a.deref());
42
43     println!("{}", a.deref());
44
45     #[allow(clippy::match_single_binding)]
46     match a.deref() {
47         _ => (),
48     }
49
50     let b: String = concat(a.deref());
51
52     let b = just_return(a).deref();
53
54     let b: String = concat(just_return(a).deref());
55
56     let b: &str = a.deref().deref();
57
58     let opt_a = Some(a.clone());
59     let b = opt_a.unwrap().deref();
60
61     // following should not require linting
62
63     let cv = CustomVec(vec![0, 42]);
64     let c = cv.deref()[0];
65
66     let b: &str = &*a.deref();
67
68     let b: String = a.deref().clone();
69
70     let b: usize = a.deref_mut().len();
71
72     let b: &usize = &a.deref().len();
73
74     let b: &str = &*a;
75
76     let b: &mut str = &mut *a;
77
78     macro_rules! expr_deref {
79         ($body:expr) => {
80             $body.deref()
81         };
82     }
83     let b: &str = expr_deref!(a);
84
85     let b: &str = expr_deref!(a.deref());
86
87     // The struct does not implement Deref trait
88     #[derive(Copy, Clone)]
89     struct NoLint(u32);
90     impl NoLint {
91         pub fn deref(self) -> u32 {
92             self.0
93         }
94         pub fn deref_mut(self) -> u32 {
95             self.0
96         }
97     }
98     let no_lint = NoLint(42);
99     let b = no_lint.deref();
100     let b = no_lint.deref_mut();
101 }