summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/tests/ui/trim_split_whitespace.rs
blob: f98451a983712c552019b4b9122f3c347eae72d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// run-rustfix
#![warn(clippy::trim_split_whitespace)]
#![allow(clippy::let_unit_value)]

struct Custom;
impl Custom {
    fn trim(self) -> Self {
        self
    }
    fn split_whitespace(self) {}
}

struct DerefStr(&'static str);
impl std::ops::Deref for DerefStr {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.0
    }
}

struct DerefStrAndCustom(&'static str);
impl std::ops::Deref for DerefStrAndCustom {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.0
    }
}
impl DerefStrAndCustom {
    fn trim(self) -> Self {
        self
    }
    fn split_whitespace(self) {}
}

struct DerefStrAndCustomSplit(&'static str);
impl std::ops::Deref for DerefStrAndCustomSplit {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.0
    }
}
impl DerefStrAndCustomSplit {
    #[allow(dead_code)]
    fn split_whitespace(self) {}
}

struct DerefStrAndCustomTrim(&'static str);
impl std::ops::Deref for DerefStrAndCustomTrim {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.0
    }
}
impl DerefStrAndCustomTrim {
    fn trim(self) -> Self {
        self
    }
}

fn main() {
    // &str
    let _ = " A B C ".trim().split_whitespace(); // should trigger lint
    let _ = " A B C ".trim_start().split_whitespace(); // should trigger lint
    let _ = " A B C ".trim_end().split_whitespace(); // should trigger lint

    // String
    let _ = (" A B C ").to_string().trim().split_whitespace(); // should trigger lint
    let _ = (" A B C ").to_string().trim_start().split_whitespace(); // should trigger lint
    let _ = (" A B C ").to_string().trim_end().split_whitespace(); // should trigger lint

    // Custom
    let _ = Custom.trim().split_whitespace(); // should not trigger lint

    // Deref<Target=str>
    let s = DerefStr(" A B C ");
    let _ = s.trim().split_whitespace(); // should trigger lint

    // Deref<Target=str> + custom impl
    let s = DerefStrAndCustom(" A B C ");
    let _ = s.trim().split_whitespace(); // should not trigger lint

    // Deref<Target=str> + only custom split_ws() impl
    let s = DerefStrAndCustomSplit(" A B C ");
    let _ = s.trim().split_whitespace(); // should trigger lint
    // Expl: trim() is called on str (deref) and returns &str.
    //       Thus split_ws() is called on str as well and the custom impl on S is unused

    // Deref<Target=str> + only custom trim() impl
    let s = DerefStrAndCustomTrim(" A B C ");
    let _ = s.trim().split_whitespace(); // should not trigger lint
}