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