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

//! # Glob

use std::{
    fmt,
    hash::{Hash, Hasher},
};

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

    /// # A string
    Str(&'a str),

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

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

impl<'a> Part<'a> {

    /// # Parses
    fn parse(mut s: &'a str) -> Vec<Self> {
        let mut result = vec![];
        loop {
            match s.find(|c| match c { '*' | '?' => true, _ => false }) {
                Some(i) => {
                    if i > 0 {
                        result.push(Part::Str(&s[..i]));
                    }
                    match s.as_bytes()[i] {
                        b'*' => if result.last() != Some(&Part::Any) {
                            result.push(Part::Any);
                        },
                        b'?' => result.push(Part::OneChar),
                        _ => {},
                    };
                    if i + 1 == s.len() {
                        break;
                    }
                    s = &s[i + 1..];
                },
                None => {
                    result.push(Part::Str(s));
                    break;
                },
            };
        }

        result
    }

}

/// # 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.
///
/// [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
#[derive(Debug, Eq)]
pub struct Glob<'a> {

    /// # Source string
    src: &'a str,

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

}

impl<'a> Glob<'a> {

    /// # Makes new instance
    pub fn new(src: &'a str) -> Self {
        Self {
            src,
            parts: Part::parse(src),
        }
    }

    /// # 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();
        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) {
                    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(),
            };
        }
    }

}

impl PartialEq for Glob<'_> {

    fn eq(&self, other: &Self) -> bool {
        self.src == other.src
    }

}

impl Hash for Glob<'_> {

    fn hash<H>(&self, h: &mut H) where H: Hasher {
        self.src.hash(h);
    }

}

/// # 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(src)
    }

}

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

    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        f.write_str(self.src)
    }

}