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]
#[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.iter().skip(1).fold(*best, |best, choice| {
&best[0..choice
.char_indices()
.zip(best.char_indices())
.take_while(|&(a, b)| a == b)
.count()]
})
choice
.iter()
.skip(1)
.fold(best.as_ref(), |best, choice| {
&best[0..choice
.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]
fn common_prefix_none() {
let input = [];
let input: [&str; 0] = [];
let output = super::common_prefix(&input);
assert_eq!(output, "");
}