async_graphql/validation/
suggestion.rs

1use std::{collections::HashMap, fmt::Write};
2
3fn levenshtein_distance(s1: &str, s2: &str) -> usize {
4    let mut column: Vec<_> = (0..=s1.len()).collect();
5    for (x, rx) in s2.bytes().enumerate() {
6        column[0] = x + 1;
7        let mut lastdiag = x;
8        for (y, ry) in s1.bytes().enumerate() {
9            let olddiag = column[y + 1];
10            if rx != ry {
11                lastdiag += 1;
12            }
13            column[y + 1] = (column[y + 1] + 1).min((column[y] + 1).min(lastdiag));
14            lastdiag = olddiag;
15        }
16    }
17    column[s1.len()]
18}
19
20pub fn make_suggestion<I, A>(prefix: &str, options: I, input: &str) -> Option<String>
21where
22    I: IntoIterator<Item = A>,
23    A: AsRef<str>,
24{
25    let mut selected = Vec::new();
26    let mut distances = HashMap::new();
27
28    for opt in options {
29        let opt = opt.as_ref().to_string();
30        let distance = levenshtein_distance(input, &opt);
31        let threshold = (input.len() / 2).max((opt.len() / 2).max(1));
32        if distance < threshold {
33            selected.push(opt.clone());
34            distances.insert(opt, distance);
35        }
36    }
37
38    if selected.is_empty() {
39        return None;
40    }
41    selected.sort_by(|a, b| distances[a].cmp(&distances[b]));
42
43    let mut suggestion =
44        String::with_capacity(prefix.len() + selected.iter().map(|s| s.len() + 5).sum::<usize>());
45    suggestion.push_str(prefix);
46    suggestion.push(' ');
47
48    for (i, s) in selected.iter().enumerate() {
49        if i != 0 {
50            suggestion.push_str(", ");
51        }
52        write!(suggestion, "\"{}\"", s).unwrap();
53    }
54
55    suggestion.push('?');
56
57    Some(suggestion)
58}