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
92
93
94
95
96
97
98
99
100
101
102
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::BuildHasher;

pub trait ValidateContains {
    fn validate_contains(&self, needle: &str) -> bool;
}

impl ValidateContains for String {
    fn validate_contains(&self, needle: &str) -> bool {
        self.contains(needle)
    }
}

impl<T> ValidateContains for Option<T>
where
    T: ValidateContains,
{
    fn validate_contains(&self, needle: &str) -> bool {
        if let Some(v) = self {
            v.validate_contains(needle)
        } else {
            true
        }
    }
}

impl<T> ValidateContains for &T
where
    T: ValidateContains,
{
    fn validate_contains(&self, needle: &str) -> bool {
        T::validate_contains(self, needle)
    }
}

impl<'cow, T> ValidateContains for Cow<'cow, T>
where
    T: ToOwned + ?Sized,
    for<'a> &'a T: ValidateContains,
{
    fn validate_contains(&self, needle: &str) -> bool {
        self.as_ref().validate_contains(needle)
    }
}

impl<'a> ValidateContains for &'a str {
    fn validate_contains(&self, needle: &str) -> bool {
        self.contains(needle)
    }
}

impl<S, H: BuildHasher> ValidateContains for HashMap<String, S, H> {
    fn validate_contains(&self, needle: &str) -> bool {
        self.contains_key(needle)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_contains_string() {
        assert!("hey".validate_contains("e"));
    }

    #[test]
    fn test_validate_contains_string_can_fail() {
        assert!(!"hey".validate_contains("o"));
    }

    #[test]
    fn test_validate_contains_hashmap_key() {
        let mut map = HashMap::new();
        map.insert("hey".to_string(), 1);
        assert!(map.validate_contains("hey"));
    }

    #[test]
    fn test_validate_contains_hashmap_key_can_fail() {
        let mut map = HashMap::new();
        map.insert("hey".to_string(), 1);
        assert!(!map.validate_contains("bob"));
    }

    #[test]
    fn test_validate_contains_cow() {
        let test: Cow<'static, str> = "hey".into();
        assert!(test.validate_contains("e"));
        let test: Cow<'static, str> = String::from("hey").into();
        assert!(test.validate_contains("e"));
    }

    #[test]
    fn test_validate_contains_cow_can_fail() {
        let test: Cow<'static, str> = "hey".into();
        assert!(!test.validate_contains("o"));
        let test: Cow<'static, str> = String::from("hey").into();
        assert!(!test.validate_contains("o"));
    }
}