1#[must_use]
17pub fn truncate(s: &str, max_len: usize) -> String {
18 if s.len() <= max_len {
19 s.to_string()
20 } else {
21 let mut truncated = s.chars().take(max_len).collect::<String>();
22 truncated.push('…');
23 truncated
24 }
25}
26
27#[cfg(test)]
28mod tests {
29 use super::*;
30
31 #[test]
32 fn truncate_short_string() {
33 assert_eq!(truncate("hi", 10), "hi");
34 }
35
36 #[test]
37 fn truncate_exact_length() {
38 assert_eq!(truncate("hello", 5), "hello");
39 }
40
41 #[test]
42 fn truncate_long_string() {
43 assert_eq!(truncate("hello world", 5), "hello…");
44 }
45
46 #[test]
47 fn truncate_empty() {
48 assert_eq!(truncate("", 5), "");
49 }
50}