firedbg_rust_debugger/
typename.rs

1/// A very crappy implementation for test case validation.
2///
3/// ```ignore
4/// assert!(wildcard_match("abc..", "abcdefg"));
5/// assert!(wildcard_match("..efg", "abcdefg"));
6/// assert!(wildcard_match("hello..world..!", "hello 100 worlds!"));
7/// ```
8pub fn wildcard_match(template: &str, against: &str) -> bool {
9    let parts: Vec<&str> = template.split("..").collect();
10    if parts.len() == 1 {
11        return template == against;
12    }
13    if !against.starts_with(parts[0]) {
14        return false;
15    }
16    let mut index = parts[0].len().max(1);
17    for i in 1..parts.len() - 1 {
18        let part = parts[i];
19        if let Some(at) = against[index..].find(part) {
20            if i > 0 && at == 0 {
21                // .. means one or more char
22                return false;
23            }
24            index += at + part.len();
25        } else {
26            return false;
27        }
28    }
29    if let Some(part) = parts.last() {
30        if part.is_empty() {
31            // template ends with ..
32            return index < against.len();
33        } else {
34            return against[index..].ends_with(part);
35        }
36    }
37    index == against.len()
38}
39
40#[cfg(test)]
41mod test {
42    use super::*;
43
44    #[test]
45    fn test_wildcard_0() {
46        assert!(wildcard_match("abc", "abc"));
47        assert!(!wildcard_match("abc", "abcd"));
48        assert!(!wildcard_match("abcd", "abc"));
49    }
50
51    #[test]
52    fn test_wildcard_1() {
53        assert!(wildcard_match("abc..", "abcdefg"));
54        assert!(!wildcard_match("abc..", "abc"));
55        assert!(wildcard_match("..efg", "abcdefg"));
56        assert!(!wildcard_match("..efg", "efg"));
57        assert!(wildcard_match("ab..c", "ab____c"));
58        assert!(wildcard_match("ab..c", "ab!c"));
59        assert!(!wildcard_match("ab..c", "a___bc"));
60        assert!(!wildcard_match("ab..c", "ab____cd"));
61        assert!(wildcard_match("(..)", "({})"));
62        assert!(wildcard_match("(..)", "(())"));
63    }
64
65    #[test]
66    fn test_wildcard_2() {
67        assert!(wildcard_match("hello..world..!", "hello world !"));
68        assert!(!wildcard_match("hello..world..!", "helloworld!"));
69        assert!(wildcard_match("hello..world..!", "hello 100 worlds!"));
70        assert!(!wildcard_match("hello..world..!", "hello world"));
71        assert!(!wildcard_match("hello..world..!", "hello worlds"));
72        assert!(wildcard_match("hello..world..", "hello world~~~"));
73        assert!(wildcard_match("..hello..world", "happy hello world"));
74        assert!(wildcard_match(
75            "..hello..world..",
76            "happy hello world forever"
77        ));
78        assert!(!wildcard_match("..hello..world..", "hello world"));
79    }
80}