pub fn truncate(s: &str, max_chars: usize) -> String {
if s.chars().count() <= max_chars {
return s.to_string();
}
if max_chars < 4 {
return s.chars().take(max_chars).collect();
}
let head: String = s.chars().take(max_chars - 3).collect();
head + "..."
}
pub fn head(s: &str, max_chars: usize) -> String {
s.chars().take(max_chars).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_strings_are_returned_unchanged() {
assert_eq!(truncate("hello", 60), "hello");
assert_eq!(truncate("", 60), "");
}
#[test]
fn a_string_exactly_at_the_limit_is_not_truncated() {
let s = "a".repeat(60);
assert_eq!(truncate(&s, 60), s);
}
#[test]
fn a_long_string_is_cut_and_marked() {
let out = truncate(&"a".repeat(100), 60);
assert_eq!(out.chars().count(), 60);
assert!(out.ends_with("..."));
}
#[test]
fn multibyte_text_is_truncated_without_panicking() {
let cjk = "日".repeat(100);
let out = truncate(&cjk, 60);
assert_eq!(out.chars().count(), 60);
assert!(out.ends_with("..."));
let emoji = "🎉".repeat(100);
assert_eq!(truncate(&emoji, 20).chars().count(), 20);
}
#[test]
fn mixed_ascii_and_multibyte_text_is_counted_in_characters() {
let s = format!("{}{}", "a".repeat(30), "日".repeat(30));
assert!(s.len() > s.chars().count(), "fixture should be mixed-width");
assert_eq!(truncate(&s, 40).chars().count(), 40);
}
#[test]
fn a_budget_too_small_for_an_ellipsis_still_returns_something() {
for n in 0..4 {
let out = truncate("abcdefgh", n);
assert_eq!(out.chars().count(), n, "n={n}");
}
}
#[test]
fn head_of_a_short_string_is_the_whole_string() {
assert_eq!(head("abc", 12), "abc");
assert_eq!(head("", 8), "");
assert_eq!(head("abcdefghijklmno", 12).chars().count(), 12);
}
#[test]
fn head_does_not_split_a_multibyte_character() {
assert_eq!(head(&"日".repeat(20), 5), "日".repeat(5));
}
}