1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 /// Find the Levenshtein distance between two strings
15 pub fn lev_distance(a: &str, b: &str) -> usize {
16 // cases which don't require further computation
18 return b.chars().count();
19 } else if b.is_empty() {
20 return a.chars().count();
23 let mut dcol: Vec<_> = (0..=b.len()).collect();
26 for (i, sc) in a.chars().enumerate() {
28 dcol[0] = current + 1;
30 for (j, tc) in b.chars().enumerate() {
31 let next = dcol[j + 1];
33 dcol[j + 1] = current;
35 dcol[j + 1] = cmp::min(current, next);
36 dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
45 /// Find the best match for a given word in the given iterator
47 /// As a loose rule to avoid the obviously incorrect suggestions, it takes
48 /// an optional limit for the maximum allowable edit distance, which defaults
49 /// to one-third of the given word.
51 /// Besides Levenshtein, we use case insensitive comparison to improve accuracy on an edge case with
52 /// a lower(upper)case letters mismatch.
53 pub fn find_best_match_for_name<'a, T>(iter_names: T,
55 dist: Option<usize>) -> Option<Symbol>
56 where T: Iterator<Item = &'a Symbol> {
57 let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d);
59 let (case_insensitive_match, levenstein_match) = iter_names
61 let dist = lev_distance(lookup, &name.as_str());
68 // Here we are collecting the next structure:
69 // (case_insensitive_match, (levenstein_match, levenstein_distance))
70 .fold((None, None), |result, (candidate, dist)| {
72 if candidate.as_str().to_uppercase() == lookup.to_uppercase() {
78 None => Some((candidate, dist)),
79 Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) })
84 if let Some(candidate) = case_insensitive_match {
85 Some(candidate) // exact case insensitive match has a higher priority
87 if let Some((candidate, _)) = levenstein_match { Some(candidate) } else { None }
92 fn test_lev_distance() {
93 use std::char::{from_u32, MAX};
94 // Test bytelength agnosticity
95 for c in (0..MAX as u32)
96 .filter_map(|i| from_u32(i))
97 .map(|i| i.to_string()) {
98 assert_eq!(lev_distance(&c[..], &c[..]), 0);
101 let a = "\nMäry häd ä little lämb\n\nLittle lämb\n";
102 let b = "\nMary häd ä little lämb\n\nLittle lämb\n";
103 let c = "Mary häd ä little lämb\n\nLittle lämb\n";
104 assert_eq!(lev_distance(a, b), 1);
105 assert_eq!(lev_distance(b, a), 1);
106 assert_eq!(lev_distance(a, c), 2);
107 assert_eq!(lev_distance(c, a), 2);
108 assert_eq!(lev_distance(b, c), 1);
109 assert_eq!(lev_distance(c, b), 1);
113 fn test_find_best_match_for_name() {
116 let input = vec![Symbol::intern("aaab"), Symbol::intern("aaabc")];
118 find_best_match_for_name(input.iter(), "aaaa", None),
119 Some(Symbol::intern("aaab"))
123 find_best_match_for_name(input.iter(), "1111111111", None),
127 let input = vec![Symbol::intern("aAAA")];
129 find_best_match_for_name(input.iter(), "AAAA", None),
130 Some(Symbol::intern("aAAA"))
133 let input = vec![Symbol::intern("AAAA")];
134 // Returns None because `lev_distance > max_dist / 3`
136 find_best_match_for_name(input.iter(), "aaaa", None),
140 let input = vec![Symbol::intern("AAAA")];
142 find_best_match_for_name(input.iter(), "aaaa", Some(4)),
143 Some(Symbol::intern("AAAA"))