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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//! # mønster (n) - pattern.
//!
//! Simple glob-style pattern matching for strings.
//! Always matches the whole string from beginning to end.
//!
//! | Wildcard | Description | Note |
//! | -------- | ----------- | ---- |
//! | *        | matches any number of any characters including none | |
//! | ?        | matches any single character | does not handle multi-byte UTF-8 codepoints |
//! | \[abc]   | matches one character given in the bracket | taken as byte values |
//! | \[a-z]   | matches one character from the range given in the bracket | range taken from their byte values |
//! | \[^abc]  | matches one character that is not given in the bracket | taken as byte values |
//! | \[^a-z]  | matches one character that is not from the range given in the bracket | range taken from their byte values |
//!
//! _Note: An empty bracket can never match anything._
//!
//! # Example
//!
//! ```
//! # use moenster::stringmatch;
//! assert!(stringmatch("m*nster", "mønster"));
//! ```

#![forbid(unsafe_code)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, future_incompatible, unreachable_pub, rust_2018_idioms)]
#![allow(clippy::collapsible_if)]

/// Match a string against the specified pattern.
///
/// Returns true if the string matches against the pattern from start to finish.
/// See the top-level documentation for allowed wildcards.
pub fn stringmatch(pattern: &str, string: &str) -> bool {
    stringmatch_bytes(pattern.as_bytes(), string.as_bytes(), Case::Sensitive)
}

// FIXME: Remove dead_code allowance.
#[allow(dead_code)]
#[derive(Copy, Clone)]
enum Case {
    Sensitive,
    Insensitive,
}

fn stringmatch_bytes(mut pattern: &[u8], mut string: &[u8], case: Case) -> bool {
    while !pattern.is_empty() && !string.is_empty() {
        match pattern[0] {
            // any number of any characters
            b'*' => {
                while pattern.len() > 2 && pattern[1] == b'*' {
                    pattern = &pattern[1..];
                }
                if pattern.len() == 1 {
                    return true;
                }

                while !string.is_empty() {
                    if stringmatch_bytes(&pattern[1..], string, case) {
                        return true;
                    }
                    string = &string[1..];
                }

                return false;
            }
            // any single character
            b'?' => {
                string = &string[1..];
            }
            // bracketed patterns such as `[abc]` or `[a-z]`
            b'[' => {
                pattern = &pattern[1..];
                let not = pattern[0] == b'^';
                if not {
                    pattern = &pattern[1..];
                }
                let mut matched = false;
                loop {
                    if pattern.is_empty() {
                        break;
                    } else if pattern[0] == b'\\' && pattern.len() >= 2 {
                        pattern = &pattern[1..];

                        if pattern[0] == string[0] {
                            matched = true;
                        }
                    } else if pattern[0] == b']' {
                        break;
                    } else if pattern.len() >= 3 && pattern[1] == b'-' {
                        let mut start = pattern[0];
                        let mut end = pattern[2];
                        let mut c = string[0];
                        if start > end {
                            std::mem::swap(&mut start, &mut end);
                        }

                        if matches!(case, Case::Insensitive) {
                            start = start.to_ascii_lowercase();
                            end = end.to_ascii_lowercase();
                            c = c.to_ascii_lowercase();
                        }

                        pattern = &pattern[2..];
                        if c >= start && c <= end {
                            matched = true;
                        }
                    } else {
                        if matches!(case, Case::Sensitive) {
                            if pattern[0] == string[0] {
                                matched = true;
                            }
                        } else {
                            if pattern[0].to_ascii_lowercase() != string[0].to_ascii_lowercase() {
                                matched = true;
                            }
                        }
                    }
                    pattern = &pattern[1..];
                }

                if not {
                    matched = !matched;
                }

                if !matched {
                    return false;
                }

                string = &string[1..];
            }
            // everything else
            _ => {
                // Ignore escaped characters
                if pattern[0] == b'\\' && pattern.len() >= 2 {
                    pattern = &pattern[1..];
                }

                let p = pattern[0];
                if matches!(case, Case::Sensitive) {
                    if p != string[0] {
                        return false;
                    }
                    string = &string[1..];
                } else {
                    if p.to_ascii_lowercase() != string[0].to_ascii_lowercase() {
                        return false;
                    }
                    string = &string[1..];
                }
            }
        }

        // Need to handle the case that a bracketed pattern wasn't properly closed and we ran out
        // of patterns to match.
        if !pattern.is_empty() {
            pattern = &pattern[1..];
        }
        if string.is_empty() {
            while !pattern.is_empty() && pattern[0] == b'*' {
                pattern = &pattern[1..];
            }
            break;
        }
    }

    pattern.is_empty() && string.is_empty()
}

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

    #[test]
    fn plain_string() {
        assert!(stringmatch("moenster", "moenster"));
    }

    #[test]
    fn escaped() {
        assert!(stringmatch("moenste\\r", "moenster"));
    }

    #[test]
    fn questionmark() {
        assert!(stringmatch("mo?nster", "moenster"));
        assert!(stringmatch("m??nster", "moenster"));
        assert!(stringmatch("mo?nst?r", "moenster"));
        assert!(!stringmatch("moenster?", "moenster"));
    }

    #[test]
    fn wildcard() {
        assert!(stringmatch("*", "moenster"));
        assert!(stringmatch("*****", "moenster"));
    }

    #[test]
    fn wildcard_and_more() {
        assert!(stringmatch("m*oenster", "moenster"));
        assert!(stringmatch("m*", "moenster"));
        assert!(stringmatch("*r", "moenster"));
    }

    #[test]
    fn bracketed_chars() {
        assert!(stringmatch("m[oei]enster", "moenster"));
        assert!(!stringmatch("m[bcd]enster", "moenster"));
    }

    #[test]
    fn not_bracketed_chars() {
        assert!(stringmatch("m[^bcd]enster", "moenster"));
        assert!(!stringmatch("m[^oei]enster", "moenster"));
    }

    #[test]
    fn bracketed_range() {
        assert!(stringmatch("m[n-p]enster", "moenster"));
        assert!(!stringmatch("m[a-c]enster", "moenster"));
    }

    #[test]
    fn not_bracketed_range() {
        assert!(stringmatch("m[^a-c]enster", "moenster"));
        assert!(!stringmatch("m[^n-p]enster", "moenster"));
    }

    #[test]
    fn wrong_bracket() {
        assert!(stringmatch("m[n-p", "mo"));
        assert!(!stringmatch("m[n-pt", "mot"));
    }

    #[test]
    fn escaped_in_bracket() {
        assert!(stringmatch("m[\\].;]o", "m]o"));
        assert!(stringmatch("m[\\].;]o", "m;o"));
        assert!(stringmatch("m[\\].;]o", "m.o"));
    }

    #[test]
    fn empty_bracket() {
        assert!(!stringmatch("m[]", "m"));
    }
}