Debian Codegraph @

src/sudo/env/wildcard_match.rs

raw symbols SCIP
1 /// Match a test input with a pattern
2 /// Only wildcard characters (*) in the pattern string have a special meaning: they match on zero or more characters
3 pub(super) fn wildcard_match(test: &[u8], pattern: &[u8]) -> bool {
4 let mut test_index = 0;
5 let mut pattern_index = 0;
6 let mut last_star = None;
7
8 loop {
9 match (pattern.get(pattern_index), test.get(test_index)) {
10 (Some(p), Some(t)) => {
11 if *p == b'*' {
12 pattern_index += 1;
13 last_star = Some((test_index, pattern_index));
14 } else if p == t {
15 pattern_index += 1;
16 test_index += 1;
17 } else if let Some((t_index, p_index)) = last_star {
18 test_index = t_index + 1;
19 pattern_index = p_index;
20 last_star = Some((test_index, pattern_index));
21 } else {
22 return false;
23 }
24 }
25 (None, Some(_)) => {
26 if let Some((t_index, p_index)) = last_star {
27 test_index = t_index + 1;
28 pattern_index = p_index;
29 last_star = Some((test_index, pattern_index));
30 } else {
31 return false;
32 }
33 }
34 (Some(b'*'), None) => {
35 pattern_index += 1;
36 }
37 (None, None) => {
38 return true;
39 }
40 _ => {
41 return false;
42 }
43 }
44 }
45 }
46
47 #[cfg(test)]
48 mod tests {
49 use super::wildcard_match;
50
51 #[test]
52 fn test_wildcard_match() {
53 let tests = vec![
54 ("foo bar", "foo *", true),
55 ("foo bar", "foo ba*", true),
56 ("foo bar", "foo *ar", true),
57 ("foo bar", "foo *r", true),
58 ("foo bar", "foo *ab", false),
59 ("foo bar", "foo r*", false),
60 ("foo bar", "*oo bar", true),
61 ("foo bar", "*f* bar", true),
62 ("foo bar", "*f bar", false),
63 ("foo ", "foo *", true),
64 ("foo", "foo *", false),
65 ("foo", "foo*", true),
66 ("foo bar", "f*******r", true),
67 ("foo******bar", "f*r", true),
68 ("foo********bar", "foo bar", false),
69 ("#%^$V@#TYH%&rot13%#@$%#$%", "#%^$V@#*t13%#@$%#$%", true),
70 ("#%^$V@#TYH%&rot13%#@$%#$%", "*%^*%&rot*%#$%", true),
71 ("#%^$V@#TYH%&rot13%#@$%#$%", "#%^$V@#TYH%&r*%#@$#$%", false),
72 ("#%^$V@#TYH%&rot13%#@$%#$%", "#%^$V@#*******@$%#$%", true),
73 ];
74
75 for (test, pattern, expected) in tests.into_iter() {
76 assert_eq!(
77 wildcard_match(test.as_bytes(), pattern.as_bytes()),
78 expected,
79 "\"{}\" {} match {}",
80 test,
81 if expected { "should" } else { "should not" },
82 pattern
83 );
84 }
85 }
86 }