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
246
247
// License: see LICENSE file at root directory of `master` branch

//! # Glob

use std::{
    borrow::Cow,
    fmt,
};

const ANY: char = '*';
const ONE_CHAR: char = '?';

/// # Parts of a `&str`
#[derive(Debug, Eq, PartialEq, Hash)]
enum Part<'a> {

    /// # A string
    Str(Cow<'a, str>),

    /// # Any (`*`)
    Any,

    /// # One character (`?`)
    OneChar,
}

macro_rules! str_to_cow {
    // Do NOT remove the casting -- we're using some dangerous tool in a safe language
    ($s: expr) => { Cow::from($s as &str) }
}

macro_rules! clone_str_to_cow {
    // Do NOT remove the casting -- we're using some dangerous tool in a safe language
    ($s: expr) => { Cow::from(String::from($s as &str)) }
}

macro_rules! parse_parts {
    ($s: ident, $str_handler: ident) => {{
        let mut result = vec![];
        loop {
            match $s.find(|c| match c { self::ANY | self::ONE_CHAR => true, _ => false }) {
                Some(i) => {
                    if i > 0 {
                        result.push(Part::Str($str_handler!(&$s[..i])));
                    }
                    match $s.as_bytes()[i] as char {
                        self::ANY => if result.last() != Some(&Part::Any) {
                            result.push(Part::Any);
                        },
                        self::ONE_CHAR => result.push(Part::OneChar),
                        _ => {},
                    };
                    if i + 1 == $s.len() {
                        break;
                    }
                    $s = &$s[i + 1..];
                },
                None => {
                    if $s.is_empty() == false {
                        result.push(Part::Str($str_handler!($s)));
                    }
                    break;
                },
            };
        }

        result
    }}
}

impl<'a> Part<'a> {

    /// # Parses a `&str`
    fn parse_str(mut s: &'a str) -> Vec<Self> {
        parse_parts!(s, str_to_cow)
    }

    /// # Parses a [`String`][r://String]
    ///
    /// [r://String]: https://doc.rust-lang.org/std/string/struct.String.html
    fn parse_string(s: String) -> Vec<Self> {
        let mut s = s.as_str();
        parse_parts!(s, clone_str_to_cow)
    }

}

/// # Glob
///
/// This struct is used to find matches from a pattern string against some string.
///
/// The pattern string supports 2 special characters: `*` and `?`:
///
/// - `*`: matches any characters or nothing at all.
/// - `?`: matches one single character.
///
/// ## Notes
///
/// - The idea is inspired by <https://en.wikipedia.org/wiki/Glob_%28programming%29>, but this is _not_ an implementation of that specification.
/// - Matches are _case sensitive_. If you want to ignore case, consider using [`to_lowercase()`][r://String/to_lowercase()] (or
///   [`to_uppercase()`][r://String/to_uppercase()]) on _both_ pattern and target string.
/// - [`Display`][r://Display] implementation prints _parsed_ pattern, not the original one.
/// - Converting from a `&str` always means borrowing its content. However converting from a [`String`][r://String] will _clone_ its content.
///
/// ## Examples
///
/// ```
/// use sub_strs::Glob;
///
/// let g = Glob::from("*r?st.rs");
/// for s in &["rust.rs", "rEst.rs", "it's rust.rs"] {
///     assert!(g.matches(s));
/// }
/// for s in &["it's not Rust", "rest", "rust!.rs"] {
///     assert!(g.matches(s) == false);
/// }
/// ```
///
/// [r://String]: https://doc.rust-lang.org/std/string/struct.String.html
/// [r://String/to_lowercase()]: https://doc.rust-lang.org/std/string/struct.String.html#method.to_lowercase
/// [r://String/to_uppercase()]: https://doc.rust-lang.org/std/string/struct.String.html#method.to_uppercase
/// [r://Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct Glob<'a> {

    /// # Parts
    parts: Vec<Part<'a>>,

}

impl<'a> Glob<'a> {

    /// # Checks if this glob matches a string
    pub fn matches<S>(&self, s: S) -> bool where S: AsRef<str> {
        let mut s = s.as_ref();

        if self.parts.is_empty() {
            return s.is_empty();
        }

        let mut parts = self.parts.iter().peekable();
        let mut must_start_with = true;
        loop {
            match parts.next() {
                Some(Part::Any) => {
                    let mut min_target_chars: usize = 0;
                    loop {
                        match parts.peek() {
                            Some(Part::Any) => drop(parts.next()),
                            Some(Part::OneChar) => {
                                parts.next();
                                min_target_chars += 1;
                            },
                            Some(Part::Str(_)) => {
                                let mut i = 0;
                                let mut chars = s.chars();
                                for _ in 0..min_target_chars {
                                    match chars.next() {
                                        Some(c) => i += c.len_utf8(),
                                        None => return false,
                                    };
                                }
                                s = &s[i..];
                                break;
                            },
                            None => return s.chars().count() >= min_target_chars,
                        };
                    }
                    must_start_with = false;
                },
                Some(Part::OneChar) => match s.chars().next() {
                    Some(c) => {
                        s = &s[c.len_utf8()..];
                        must_start_with = true;
                    },
                    None => return false,
                },
                Some(Part::Str(sub)) => match s.find(sub.as_ref()) {
                    Some(i) if i == 0 || must_start_with == false => {
                        s = &s[i + sub.len()..];
                        must_start_with = true;
                    },
                    _ => return false,
                },
                None => return s.is_empty(),
            };
        }
    }

}

/// # Converts from a `&str` to [`Glob`][::Glob]
///
/// [::Glob]: struct.Glob.html
impl<'a> From<&'a str> for Glob<'a> {

    fn from(src: &'a str) -> Self {
        Self {
            parts: Part::parse_str(src),
        }
    }

}

/// # Converts from a [`&String`][r://String] to [`Glob`][::Glob]
///
/// [::Glob]: struct.Glob.html
/// [r://String]: https://doc.rust-lang.org/std/string/struct.String.html
impl<'a> From<&'a String> for Glob<'a> {

    fn from(src: &'a String) -> Self {
        Self::from(src.as_str())
    }

}

/// # Converts from a [`String`][r://String] to [`Glob`][::Glob]
///
/// [::Glob]: struct.Glob.html
/// [r://String]: https://doc.rust-lang.org/std/string/struct.String.html
impl From<String> for Glob<'_> {

    fn from(src: String) -> Self {
        Self {
            parts: Part::parse_string(src),
        }
    }

}

impl fmt::Display for Glob<'_> {

    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        use fmt::Write;

        for p in self.parts.iter() {
            match p {
                Part::Str(s) => f.write_str(s)?,
                Part::Any => f.write_char(ANY)?,
                Part::OneChar => f.write_char(ONE_CHAR)?,
            };
        }

        Ok(())
    }

}