1 //! Edit distances.
2 //!
3 //! The [edit distance] is a metric for measuring the difference between two strings.
4 //!
5 //! [edit distance]: https://en.wikipedia.org/wiki/Edit_distance
6
7 // The current implementation is the restricted Damerau-Levenshtein algorithm. It is restricted
8 // because it does not permit modifying characters that have already been transposed. The specific
9 // algorithm should not matter to the caller of the methods, which is why it is not noted in the
10 // documentation.
11
12 use crate::symbol::Symbol;
13 use std::{cmp, mem};
14
15 #[cfg(test)]
16 mod tests;
17
18 /// Finds the [edit distance] between two strings.
19 ///
20 /// Returns `None` if the distance exceeds the limit.
21 ///
22 /// [edit distance]: https://en.wikipedia.org/wiki/Edit_distance
edit_distance(a: &str, b: &str, limit: usize) -> Option<usize>23 pub fn edit_distance(a: &str, b: &str, limit: usize) -> Option<usize> {
24 let mut a = &a.chars().collect::<Vec<_>>()[..];
25 let mut b = &b.chars().collect::<Vec<_>>()[..];
26
27 // Ensure that `b` is the shorter string, minimizing memory use.
28 if a.len() < b.len() {
29 mem::swap(&mut a, &mut b);
30 }
31
32 let min_dist = a.len() - b.len();
33 // If we know the limit will be exceeded, we can return early.
34 if min_dist > limit {
35 return None;
36 }
37
38 // Strip common prefix.
39 while let Some(((b_char, b_rest), (a_char, a_rest))) = b.split_first().zip(a.split_first())
40 && a_char == b_char
41 {
42 a = a_rest;
43 b = b_rest;
44 }
45 // Strip common suffix.
46 while let Some(((b_char, b_rest), (a_char, a_rest))) = b.split_last().zip(a.split_last())
47 && a_char == b_char
48 {
49 a = a_rest;
50 b = b_rest;
51 }
52
53 // If either string is empty, the distance is the length of the other.
54 // We know that `b` is the shorter string, so we don't need to check `a`.
55 if b.len() == 0 {
56 return Some(min_dist);
57 }
58
59 let mut prev_prev = vec![usize::MAX; b.len() + 1];
60 let mut prev = (0..=b.len()).collect::<Vec<_>>();
61 let mut current = vec![0; b.len() + 1];
62
63 // row by row
64 for i in 1..=a.len() {
65 current[0] = i;
66 let a_idx = i - 1;
67
68 // column by column
69 for j in 1..=b.len() {
70 let b_idx = j - 1;
71
72 // There is no cost to substitute a character with itself.
73 let substitution_cost = if a[a_idx] == b[b_idx] { 0 } else { 1 };
74
75 current[j] = cmp::min(
76 // deletion
77 prev[j] + 1,
78 cmp::min(
79 // insertion
80 current[j - 1] + 1,
81 // substitution
82 prev[j - 1] + substitution_cost,
83 ),
84 );
85
86 if (i > 1) && (j > 1) && (a[a_idx] == b[b_idx - 1]) && (a[a_idx - 1] == b[b_idx]) {
87 // transposition
88 current[j] = cmp::min(current[j], prev_prev[j - 2] + 1);
89 }
90 }
91
92 // Rotate the buffers, reusing the memory.
93 [prev_prev, prev, current] = [prev, current, prev_prev];
94 }
95
96 // `prev` because we already rotated the buffers.
97 let distance = prev[b.len()];
98 (distance <= limit).then_some(distance)
99 }
100
101 /// Provides a word similarity score between two words that accounts for substrings being more
102 /// meaningful than a typical edit distance. The lower the score, the closer the match. 0 is an
103 /// identical match.
104 ///
105 /// Uses the edit distance between the two strings and removes the cost of the length difference.
106 /// If this is 0 then it is either a substring match or a full word match, in the substring match
107 /// case we detect this and return `1`. To prevent finding meaningless substrings, eg. "in" in
108 /// "shrink", we only perform this subtraction of length difference if one of the words is not
109 /// greater than twice the length of the other. For cases where the words are close in size but not
110 /// an exact substring then the cost of the length difference is discounted by half.
111 ///
112 /// Returns `None` if the distance exceeds the limit.
edit_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<usize>113 pub fn edit_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<usize> {
114 let n = a.chars().count();
115 let m = b.chars().count();
116
117 // Check one isn't less than half the length of the other. If this is true then there is a
118 // big difference in length.
119 let big_len_diff = (n * 2) < m || (m * 2) < n;
120 let len_diff = if n < m { m - n } else { n - m };
121 let distance = edit_distance(a, b, limit + len_diff)?;
122
123 // This is the crux, subtracting length difference means exact substring matches will now be 0
124 let score = distance - len_diff;
125
126 // If the score is 0 but the words have different lengths then it's a substring match not a full
127 // word match
128 let score = if score == 0 && len_diff > 0 && !big_len_diff {
129 1 // Exact substring match, but not a total word match so return non-zero
130 } else if !big_len_diff {
131 // Not a big difference in length, discount cost of length difference
132 score + (len_diff + 1) / 2
133 } else {
134 // A big difference in length, add back the difference in length to the score
135 score + len_diff
136 };
137
138 (score <= limit).then_some(score)
139 }
140
141 /// Finds the best match for given word in the given iterator where substrings are meaningful.
142 ///
143 /// A version of [`find_best_match_for_name`] that uses [`edit_distance_with_substrings`] as the
144 /// score for word similarity. This takes an optional distance limit which defaults to one-third of
145 /// the given word.
146 ///
147 /// We use case insensitive comparison to improve accuracy on an edge case with a lower(upper)case
148 /// letters mismatch.
find_best_match_for_name_with_substrings( candidates: &[Symbol], lookup: Symbol, dist: Option<usize>, ) -> Option<Symbol>149 pub fn find_best_match_for_name_with_substrings(
150 candidates: &[Symbol],
151 lookup: Symbol,
152 dist: Option<usize>,
153 ) -> Option<Symbol> {
154 find_best_match_for_name_impl(true, candidates, lookup, dist)
155 }
156
157 /// Finds the best match for a given word in the given iterator.
158 ///
159 /// As a loose rule to avoid the obviously incorrect suggestions, it takes
160 /// an optional limit for the maximum allowable edit distance, which defaults
161 /// to one-third of the given word.
162 ///
163 /// We use case insensitive comparison to improve accuracy on an edge case with a lower(upper)case
164 /// letters mismatch.
find_best_match_for_name( candidates: &[Symbol], lookup: Symbol, dist: Option<usize>, ) -> Option<Symbol>165 pub fn find_best_match_for_name(
166 candidates: &[Symbol],
167 lookup: Symbol,
168 dist: Option<usize>,
169 ) -> Option<Symbol> {
170 find_best_match_for_name_impl(false, candidates, lookup, dist)
171 }
172
173 #[cold]
find_best_match_for_name_impl( use_substring_score: bool, candidates: &[Symbol], lookup_symbol: Symbol, dist: Option<usize>, ) -> Option<Symbol>174 fn find_best_match_for_name_impl(
175 use_substring_score: bool,
176 candidates: &[Symbol],
177 lookup_symbol: Symbol,
178 dist: Option<usize>,
179 ) -> Option<Symbol> {
180 let lookup = lookup_symbol.as_str();
181 let lookup_uppercase = lookup.to_uppercase();
182
183 // Priority of matches:
184 // 1. Exact case insensitive match
185 // 2. Edit distance match
186 // 3. Sorted word match
187 if let Some(c) = candidates.iter().find(|c| c.as_str().to_uppercase() == lookup_uppercase) {
188 return Some(*c);
189 }
190
191 let mut dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3);
192 let mut best = None;
193 // store the candidates with the same distance, only for `use_substring_score` current.
194 let mut next_candidates = vec![];
195 for c in candidates {
196 match if use_substring_score {
197 edit_distance_with_substrings(lookup, c.as_str(), dist)
198 } else {
199 edit_distance(lookup, c.as_str(), dist)
200 } {
201 Some(0) => return Some(*c),
202 Some(d) => {
203 if use_substring_score {
204 if d < dist {
205 dist = d;
206 next_candidates.clear();
207 } else {
208 // `d == dist` here, we need to store the candidates with the same distance
209 // so we won't decrease the distance in the next loop.
210 }
211 next_candidates.push(*c);
212 } else {
213 dist = d - 1;
214 }
215 best = Some(*c);
216 }
217 None => {}
218 }
219 }
220
221 // We have a tie among several candidates, try to select the best among them ignoring substrings.
222 // For example, the candidates list `force_capture`, `capture`, and user inputted `forced_capture`,
223 // we select `force_capture` with a extra round of edit distance calculation.
224 if next_candidates.len() > 1 {
225 debug_assert!(use_substring_score);
226 best = find_best_match_for_name_impl(
227 false,
228 &next_candidates,
229 lookup_symbol,
230 Some(lookup.len()),
231 );
232 }
233 if best.is_some() {
234 return best;
235 }
236
237 find_match_by_sorted_words(candidates, lookup)
238 }
239
find_match_by_sorted_words(iter_names: &[Symbol], lookup: &str) -> Option<Symbol>240 fn find_match_by_sorted_words(iter_names: &[Symbol], lookup: &str) -> Option<Symbol> {
241 iter_names.iter().fold(None, |result, candidate| {
242 if sort_by_words(candidate.as_str()) == sort_by_words(lookup) {
243 Some(*candidate)
244 } else {
245 result
246 }
247 })
248 }
249
sort_by_words(name: &str) -> String250 fn sort_by_words(name: &str) -> String {
251 let mut split_words: Vec<&str> = name.split('_').collect();
252 // We are sorting primitive &strs and can use unstable sort here.
253 split_words.sort_unstable();
254 split_words.join("_")
255 }
256