Skip to content

Commit

Permalink
fix(distance): Fix division by zero when comparing empty strings
Browse files Browse the repository at this point in the history
  • Loading branch information
Holzhaus committed Dec 30, 2024
1 parent ae666a0 commit 14306b3
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/distance/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,16 @@ pub fn between(lhs: &str, rhs: &str) -> Distance {
let lhs = normalize(lhs);
let rhs = normalize(rhs);

let levenshtein_distance = levenshtein(&lhs, &rhs);
let max_possible_distance = cmp::max(lhs.len(), rhs.len());

// Special case: If both strings are empty after normalization, then the strings should be
// considered equal and we can exit early. Otherwise we would divide by zero later on.
if max_possible_distance == 0 {
return Distance::MIN;
}

let levenshtein_distance = levenshtein(&lhs, &rhs);

// FIXME: It's extremely unlikely, but this conversion to f64 is fallible. Hence, it should use
// f64::try_from(usize) instead, but unfortunately that doesn't exist.
Distance::from(levenshtein_distance as f64 / max_possible_distance as f64)
Expand Down

0 comments on commit 14306b3

Please sign in to comment.