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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// License: see LICENSE file at root directory of `master` branch

//! # Glob

use std::{
    borrow::Cow,
    collections::HashMap,
    fmt::{self, Display, Formatter},
    io::{self, Error},
    str::FromStr,
};

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)
    }

}

/// # Sub string, used in Glob::matches()
#[derive(Debug)]
struct SubStr {
    fixed: bool,
    idx: usize,
}

/// # 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 or any other
///   specifications.
/// - 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.
/// - Implementations of `From<&'a str>` and `From<&'a String>` always borrow the source string.
/// - Implementations of `FromStr` and `From<String>` will _clone_ the source string.
///
/// ## Examples
///
/// <!-- NOTE: these examples are also *essential* tests, do NOT change or remove them. -->
///
/// ```
/// 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: Vec<Part<'a>>,
    sub_str_count: usize,
}

impl<'a> Glob<'a> {

    /// # Makes new instance
    fn new(parts: Vec<Part<'a>>) -> Self {
        let sub_str_count = parts.iter().filter(|p| match p { Part::Str(_) => true, _ => false }).count();
        Self {
            parts,
            sub_str_count,
        }
    }

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

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

        let mut map = match self.make_map(s) {
            Some(map) => map,
            None => return false,
        };
        loop {
            let mut char_count: usize = 0;
            for (part_idx, part) in self.parts.iter().enumerate() {
                match part {
                    Part::Any => {},
                    Part::OneChar => char_count += 1,
                    Part::Str(sub) => if char_count > 0 && s.chars().take(char_count).count() < char_count {
                        match map.get_mut(&part_idx) {
                            Some(SubStr { fixed, idx: sub_idx }) => match fixed {
                                true => return false,
                                false => match s[*sub_idx..].chars().next() {
                                    Some(c) => match s[*sub_idx + c.len_utf8()..].find(sub.as_ref()) {
                                        Some(i) => {
                                            *sub_idx = i;
                                            break;
                                        },
                                        None => return false,
                                    },
                                    None => return false,
                                },
                            },
                            // This is internal error
                            None => return false,
                        };
                    },
                };

                if part_idx + 1 == self.parts.len() {
                    return true;
                }
            }
        }
    }

    /// # Makes map
    fn make_map(&self, s: &str) -> Option<HashMap<usize, SubStr>> {
        let mut result = HashMap::with_capacity(self.sub_str_count);
        let mut dynamic = false;
        let mut idx = 0;
        for (part_idx, part) in self.parts.iter().enumerate() {
            match part {
                Part::Str(sub) => {
                    let fixed;
                    let sub_idx;
                    if part_idx == 0 {
                        match s.starts_with(sub.as_ref()) {
                            true => {
                                fixed = true;
                                sub_idx = 0;
                            },
                            false => return None,
                        };
                    } else if part_idx + 1 == self.parts.len() {
                        match s.ends_with(sub.as_ref()) {
                            true => {
                                fixed = true;
                                sub_idx = s.len() - sub.len();
                            },
                            false => return None,
                        };
                    } else {
                        fixed = dynamic == false;
                        sub_idx = match s[idx..].find(sub.as_ref()) {
                            Some(i) => {
                                idx = i + sub.len();
                                i
                            },
                            None => return None,
                        };
                    }
                    result.insert(part_idx, SubStr { fixed, idx: sub_idx });
                },
                Part::Any => dynamic = true,
                Part::OneChar => match s[idx..].chars().next() {
                    Some(c) => idx += c.len_utf8(),
                    None => return None,
                },
            };
        }

        Some(result)
    }

}

/// # 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::new(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::new(Part::parse_string(src))
    }

}

impl<'a> From<Cow<'a, str>> for Glob<'a> {

    fn from(s: Cow<'a, str>) -> Self {
        match s {
            Cow::Borrowed(s) => Self::from(s),
            Cow::Owned(s) => Self::from(s),
        }
    }

}

impl FromStr for Glob<'_> {

    type Err = Error;

    fn from_str(s: &str) -> io::Result<Self> {
        Ok(Self::from(String::from(s)))
    }

}

impl Display for Glob<'_> {

    fn fmt(&self, f: &mut 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(())
    }

}