1 //! Levenshtein distances.
2 //!
3 //! The [Levenshtein distance] is a metric for measuring the difference between two strings.
4 //!
5 //! [Levenshtein distance]: https://en.wikipedia.org/wiki/Levenshtein_distance
6
7 use crate::symbol::Symbol;
8 use std::cmp;
9
10 #[cfg(test)]
11 mod tests;
12
13 /// Finds the Levenshtein distance between two strings.
lev_distance(a: &str, b: &str) -> usize14 pub fn lev_distance(a: &str, b: &str) -> usize {
15 // cases which don't require further computation
16 if a.is_empty() {
17 return b.chars().count();
18 } else if b.is_empty() {
19 return a.chars().count();
20 }
21
22 let mut dcol: Vec<_> = (0..=b.len()).collect();
23 let mut t_last = 0;
24
25 for (i, sc) in a.chars().enumerate() {
26 let mut current = i;
27 dcol[0] = current + 1;
28
29 for (j, tc) in b.chars().enumerate() {
30 let next = dcol[j + 1];
31 if sc == tc {
32 dcol[j + 1] = current;
33 } else {
34 dcol[j + 1] = cmp::min(current, next);
35 dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
36 }
37 current = next;
38 t_last = j;
39 }
40 }
41 dcol[t_last + 1]
42 }
43
44 /// Finds the best match for a given word in the given iterator.
45 ///
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.
49 ///
50 /// Besides Levenshtein, we use case insensitive comparison to improve accuracy
51 /// on an edge case with a lower(upper)case letters mismatch.
52 #[cold]
find_best_match_for_name( name_vec: &[Symbol], lookup: Symbol, dist: Option<usize>, ) -> Option<Symbol>53 pub fn find_best_match_for_name(
54 name_vec: &[Symbol],
55 lookup: Symbol,
56 dist: Option<usize>,
57 ) -> Option<Symbol> {
58 let lookup = &lookup.as_str();
59 let max_dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3);
60
61 let (case_insensitive_match, levenshtein_match) = name_vec
62 .iter()
63 .filter_map(|&name| {
64 let dist = lev_distance(lookup, &name.as_str());
65 if dist <= max_dist { Some((name, dist)) } else { None }
66 })
67 // Here we are collecting the next structure:
68 // (case_insensitive_match, (levenshtein_match, levenshtein_distance))
69 .fold((None, None), |result, (candidate, dist)| {
70 (
71 if candidate.as_str().to_uppercase() == lookup.to_uppercase() {
72 Some(candidate)
73 } else {
74 result.0
75 },
76 match result.1 {
77 None => Some((candidate, dist)),
78 Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }),
79 },
80 )
81 });
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 {
87 Some(candidate)
88 } else if levenshtein_match.is_some() {
89 levenshtein_match.map(|(candidate, _)| candidate)
90 } else {
91 find_match_by_sorted_words(name_vec, lookup)
92 }
93 }
94
find_match_by_sorted_words(iter_names: &[Symbol], lookup: &str) -> Option<Symbol>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) {
98 Some(*candidate)
99 } else {
100 result
101 }
102 })
103 }
104
sort_by_words(name: &str) -> String105 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("_")
110 }
111