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 let (case_insensitive_match, levenshtein_match) = name_vec
64 let dist = lev_distance(lookup, &name.as_str());
65 if dist <= max_dist { Some((name, dist)) } else { None }
67 // Here we are collecting the next structure:
68 // (case_insensitive_match, (levenshtein_match, levenshtein_distance))
69 .fold((None, None), |result, (candidate, dist)| {
71 if candidate.as_str().to_uppercase() == lookup.to_uppercase() {
77 None => Some((candidate, dist)),
78 Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }),
82 // Priority of matches:
83 // 1. Exact case insensitive match
84 // 2. Levenshtein distance match
85 // 3. Sorted word match
86 if let Some(candidate) = case_insensitive_match {
88 } else if levenshtein_match.is_some() {
89 levenshtein_match.map(|(candidate, _)| candidate)
91 find_match_by_sorted_words(name_vec, lookup)
95 fn find_match_by_sorted_words(iter_names: &[Symbol], lookup: &str) -> Option<Symbol> {
96 iter_names.iter().fold(None, |result, candidate| {
97 if sort_by_words(&candidate.as_str()) == sort_by_words(lookup) {
105 fn sort_by_words(name: &str) -> String {
106 let mut split_words: Vec<&str> = name.split('_').collect();
107 // We are sorting primitive &strs and can use unstable sort here.
108 split_words.sort_unstable();
109 split_words.join("_")