diff --git a/crates/util/src/lib.rs b/crates/util/src/lib.rs index 0e270db906..ea8fdee2a8 100644 --- a/crates/util/src/lib.rs +++ b/crates/util/src/lib.rs @@ -46,10 +46,10 @@ pub fn truncate(s: &str, max_chars: usize) -> &str { pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String { debug_assert!(max_chars >= 5); - if s.len() > max_chars { - format!("{}…", truncate(s, max_chars.saturating_sub(3))) - } else { - s.to_string() + let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars); + match truncation_ix { + Some(length) => s[..length].to_string() + "…", + None => s.to_string(), } } @@ -279,12 +279,9 @@ mod tests { #[test] fn test_trancate_and_trailoff() { - const MAX_CHARS: usize = 24; - assert_eq!( - truncate_and_trailoff("ajouter un compte d'èèèès", MAX_CHARS), - "ajouter un compte d'è…" - ); - assert_eq!(truncate_and_trailoff("ajouter", MAX_CHARS), "ajouter"); - assert_eq!(truncate_and_trailoff("", MAX_CHARS), ""); + assert_eq!(truncate_and_trailoff("", 5), ""); + assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè"); + assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè"); + assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…"); } }