Skip to content

Commit

Permalink
Merge pull request #5879 from therealprof/features/suggestions-use-in…
Browse files Browse the repository at this point in the history
…sertion-sort

Replace another sort_by call by a manual insertion with a binary_search
  • Loading branch information
epage authored Jan 9, 2025
2 parents 26f23e4 + 4f448df commit a7f6acf
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions clap_builder/src/parser/features/suggestions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
#[cfg(feature = "suggestions")]
use std::cmp::Ordering;

// Internal
use crate::builder::Command;

Expand All @@ -13,15 +10,29 @@ where
T: AsRef<str>,
I: IntoIterator<Item = T>,
{
let mut candidates: Vec<(f64, String)> = possible_values
.into_iter()
use std::cmp::Ordering;

let mut candidates: Vec<(f64, String)> = Vec::new();
for pv in possible_values {
// GH #4660: using `jaro` because `jaro_winkler` implementation in `strsim-rs` is wrong
// causing strings with common prefix >=10 to be considered perfectly similar
.map(|pv| (strsim::jaro(v, pv.as_ref()), pv.as_ref().to_owned()))
// Confidence of 0.7 so that bar -> baz is suggested
.filter(|(confidence, _)| *confidence > 0.7)
.collect();
candidates.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));
let confidence = strsim::jaro(v, pv.as_ref());

if confidence > 0.7 {
let new_elem = (confidence, pv.as_ref().to_owned());
let pos = candidates
.binary_search_by(|probe| {
if probe.0 > confidence {
Ordering::Greater
} else {
Ordering::Less
}
})
.unwrap_or_else(|e| e);
candidates.insert(pos, new_elem);
}
}

candidates.into_iter().map(|(_, pv)| pv).collect()
}

Expand Down

0 comments on commit a7f6acf

Please sign in to comment.