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
//! A fast implementation (`O(n)`) of fuzzy-filtering.

/// This function takes two strings: the filter, and the string to test against ("other").
/// It runs through "other" and determines if it matches "filter", and returns the resulting `bool`
pub fn matches<'a>(filter: &'a str, other: &'a str) -> bool {
  let fzy = FuzzyFilter { filter };
  fzy.matches(other)
}

/// A re-usable struct that you can repeatedly call `matches(...)` against
pub struct FuzzyFilter<'a> {
  filter: &'a str,
}
impl<'a> FuzzyFilter<'a> {
  /// Constructs a `FuzzyFilter` instance with the given filter.
  pub fn new(filter: &'a str) -> FuzzyFilter {
    FuzzyFilter { filter }
  }

  /// This function takes the string to test the filter against ("other").
  /// It runs through "other", determines if it matches the stored "filter"
  /// and returns the resulting `bool`
  pub fn matches(&self, other: &'a str) -> bool {
    let mut filter_chars = self.filter.chars().peekable();
    for other_c in other.chars() {
      // advance filter_chars iff other_chars.next() == filter_chars.peek()
      match filter_chars.peek() {
        Some(filter_c) if *filter_c == other_c => {
          filter_chars.next();
        }
        _ => {}
      }

      // if we've reached the end of filter_chars,
      // return true
      if filter_chars.peek().is_none() {
        return true;
      }
    }
    false
  }
}

#[cfg(test)]
mod tests {
  use crate::matches;

  #[test]
  fn empty() {
    assert_eq!(matches("", ""), false);
  }

  #[test]
  fn exact() {
    assert_eq!(matches("abc", "abc"), true);
  }

  #[test]
  fn test1() {
    assert_eq!(matches("abc", "alpha beta"), false);
    assert_eq!(matches("abc", "alpha beta charlie"), true);
  }

  #[test]
  fn test2() {
    assert_eq!(matches("ppb", "pepsi polar bears"), true);
    assert_eq!(matches("ppbz", "pepsi polar bears"), false);
    assert_eq!(matches("ppbs", "pepsi polar bears"), true);
  }
}