alpha2-diagnose 0.10.0

Format-neutral document diagnostics for alpha2: a document tree, a JSON reader that recovers, a schema walker, advice and fixes.
Documentation
//! Close names: edit distance, one candidate or a short list.

/// The most candidates a list answers.
pub const MAX_CANDIDATES: usize = 8;

/// What [`closest`] found.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Suggestion<'a> {
    /// One candidate nearer than every other.
    One(&'a str),
    /// Several equally near ones, nearest first, at most [`MAX_CANDIDATES`].
    Several(Vec<&'a str>),
    /// Nothing near.
    None,
}

/// The edit distance of `a` and `b` (optimal string alignment: insertions, deletions,
/// substitutions and swaps of neighbors), or `None` past `limit`.
#[must_use]
pub fn distance(a: &str, b: &str, limit: usize) -> Option<usize> {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    if a.len().abs_diff(b.len()) > limit {
        return None;
    }
    let width = b.len() + 1;
    let mut previous2 = vec![0; width];
    let mut previous: Vec<usize> = (0..width).collect();
    let mut current = vec![0; width];
    for i in 1..=a.len() {
        current[0] = i;
        let mut row_min = current[0];
        for j in 1..=b.len() {
            let cost = usize::from(a[i - 1] != b[j - 1]);
            let mut best = (previous[j] + 1)
                .min(current[j - 1] + 1)
                .min(previous[j - 1] + cost);
            if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
                best = best.min(previous2[j - 2] + 1);
            }
            current[j] = best;
            row_min = row_min.min(best);
        }
        if row_min > limit {
            return None;
        }
        std::mem::swap(&mut previous2, &mut previous);
        std::mem::swap(&mut previous, &mut current);
    }
    let found = previous[b.len()];
    (found <= limit).then_some(found)
}

/// Whether two names are one name written another way: case, `_` and `-` ignored.
#[must_use]
pub fn same_name(a: &str, b: &str) -> bool {
    let fold = |text: &str| -> String {
        text.chars()
            .filter(|char| !matches!(char, '_' | '-' | ' '))
            .flat_map(char::to_lowercase)
            .collect()
    };
    fold(a) == fold(b)
}

/// The largest distance at which a name of `length` characters counts as near.
#[must_use]
pub const fn limit_for(length: usize) -> usize {
    match length {
        0..=2 => 1,
        3..=5 => 2,
        _ => 3,
    }
}

/// The candidates near `name`: one when it is nearer than every other, else every one at the
/// nearest distance, nearest first.
#[must_use]
pub fn closest<'a>(name: &str, candidates: impl IntoIterator<Item = &'a str>) -> Suggestion<'a> {
    let limit = limit_for(name.chars().count());
    let mut near: Vec<(usize, &str)> = candidates
        .into_iter()
        .filter(|candidate| *candidate != name)
        .filter_map(|candidate| {
            if same_name(name, candidate) {
                return Some((0, candidate));
            }
            distance(
                name,
                candidate,
                limit.min(limit_for(candidate.chars().count())),
            )
            .map(|found| (found, candidate))
        })
        .collect();
    near.sort_unstable();
    near.dedup_by(|a, b| a.1 == b.1);
    match near.as_slice() {
        [] => Suggestion::None,
        [(_, only)] => Suggestion::One(only),
        [(first, best), (second, _), ..] if first < second => Suggestion::One(best),
        list => {
            let nearest = list[0].0;
            Suggestion::Several(
                list.iter()
                    .take_while(|(found, _)| *found == nearest)
                    .take(MAX_CANDIDATES)
                    .map(|(_, candidate)| *candidate)
                    .collect(),
            )
        }
    }
}

/// Names as a short list for a help line: `"a", "b" and 3 more`.
#[must_use]
pub fn listed<'a>(names: impl IntoIterator<Item = &'a str>, shown: usize) -> String {
    let names: Vec<String> = names.into_iter().map(crate::write::quote).collect();
    if names.len() <= shown {
        return names.join(", ");
    }
    format!(
        "{} and {} more",
        names[..shown].join(", "),
        names.len() - shown
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn distance_counts_a_swap_as_one() {
        assert_eq!(distance("opactiy", "opacity", 3), Some(1));
        assert_eq!(distance("caption", "captions", 3), Some(1));
        assert_eq!(distance("kitten", "sitting", 3), Some(3));
        assert_eq!(distance("kitten", "sitting", 2), None);
        assert_eq!(distance("", "abc", 3), Some(3));
    }

    #[test]
    fn same_name_ignores_case_and_separators() {
        assert!(same_name("sourceId", "source_id"));
        assert!(same_name("Source-ID", "source_id"));
        assert!(!same_name("source", "source_id"));
    }

    #[test]
    fn closest_answers_one_or_a_list() {
        let fields = ["opacity", "position", "scale", "rotation_degrees", "anchor"];
        assert_eq!(closest("opactiy", fields), Suggestion::One("opacity"));
        assert_eq!(closest("sclae", fields), Suggestion::One("scale"));
        assert_eq!(closest("zzzz", fields), Suggestion::None);
        assert_eq!(
            closest("ab", ["ac", "ad", "xyz"]),
            Suggestion::Several(vec!["ac", "ad"])
        );
        assert_eq!(
            closest("sourceId", ["source_id", "sources"]),
            Suggestion::One("source_id")
        );
        assert_eq!(closest("opacity", ["opacity"]), Suggestion::None);
    }

    #[test]
    fn listed_caps_the_names() {
        assert_eq!(listed(["a", "b", "c"], 2), "\"a\", \"b\" and 1 more");
        assert_eq!(listed(["a"], 2), "\"a\"");
    }
}