1 //! Levenshtein distances.
3 //! The [Levenshtein distance] is a metric for measuring the difference between two strings.
5 //! [Levenshtein distance]: https://en.wikipedia.org/wiki/Levenshtein_distance
7 use crate::symbol::Symbol;
13 /// Finds the Levenshtein distance between two strings.
14 pub fn lev_distance(a: &str, b: &str) -> usize {
15 // cases which don't require further computation
17 return b.chars().count();
18 } else if b.is_empty() {
19 return a.chars().count();
22 let mut dcol: Vec<_> = (0..=b.len()).collect();
25 for (i, sc) in a.chars().enumerate() {
27 dcol[0] = current + 1;
29 for (j, tc) in b.chars().enumerate() {
30 let next = dcol[j + 1];
32 dcol[j + 1] = current;
34 dcol[j + 1] = cmp::min(current, next);
35 dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
44 /// Finds the best match for a given word in the given iterator.
46 /// As a loose rule to avoid the obviously incorrect suggestions, it takes
47 /// an optional limit for the maximum allowable edit distance, which defaults
48 /// to one-third of the given word.
50 /// Besides Levenshtein, we use case insensitive comparison to improve accuracy
51 /// on an edge case with a lower(upper)case letters mismatch.
53 pub fn find_best_match_for_name(
58 let lookup = lookup.as_str();
59 let max_dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3);
61 // Priority of matches:
62 // 1. Exact case insensitive match
63 // 2. Levenshtein distance match
64 // 3. Sorted word match
65 if let Some(case_insensitive_match) =
66 name_vec.iter().find(|candidate| candidate.as_str().to_uppercase() == lookup.to_uppercase())
68 return Some(*case_insensitive_match);
70 let levenshtein_match = name_vec
73 let dist = lev_distance(lookup, name.as_str());
74 if dist <= max_dist { Some((name, dist)) } else { None }
76 // Here we are collecting the next structure:
77 // (levenshtein_match, levenshtein_distance)
78 .fold(None, |result, (candidate, dist)| match result {
79 None => Some((candidate, dist)),
80 Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }),
82 if levenshtein_match.is_some() {
83 levenshtein_match.map(|(candidate, _)| candidate)
85 find_match_by_sorted_words(name_vec, lookup)
89 fn find_match_by_sorted_words(iter_names: &[Symbol], lookup: &str) -> Option<Symbol> {
90 iter_names.iter().fold(None, |result, candidate| {
91 if sort_by_words(candidate.as_str()) == sort_by_words(lookup) {
99 fn sort_by_words(name: &str) -> String {
100 let mut split_words: Vec<&str> = name.split('_').collect();
101 // We are sorting primitive &strs and can use unstable sort here.
102 split_words.sort_unstable();
103 split_words.join("_")