Generalize common_prefix for AsStr inputs.

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
dasha_uwu
2025-11-01 01:52:33 +00:00
committed by Jason Volk
parent 06618eadab
commit 888f72d8d0
2 changed files with 13 additions and 9 deletions

View File

@@ -93,15 +93,19 @@ where
/// ``` /// ```
#[must_use] #[must_use]
#[allow(clippy::string_slice)] #[allow(clippy::string_slice)]
pub fn common_prefix<'a>(choice: &'a [&str]) -> &'a str { pub fn common_prefix<T: AsRef<str>>(choice: &[T]) -> &str {
choice.first().map_or(EMPTY, move |best| { choice.first().map_or(EMPTY, move |best| {
choice.iter().skip(1).fold(*best, |best, choice| { choice
&best[0..choice .iter()
.char_indices() .skip(1)
.zip(best.char_indices()) .fold(best.as_ref(), |best, choice| {
.take_while(|&(a, b)| a == b) &best[0..choice
.count()] .as_ref()
}) .char_indices()
.zip(best.char_indices())
.take_while(|&(a, b)| a == b)
.count()]
})
}) })
} }

View File

@@ -16,7 +16,7 @@ fn common_prefix_empty() {
#[test] #[test]
fn common_prefix_none() { fn common_prefix_none() {
let input = []; let input: [&str; 0] = [];
let output = super::common_prefix(&input); let output = super::common_prefix(&input);
assert_eq!(output, ""); assert_eq!(output, "");
} }