1pub fn truncate(s: &str, max_chars: usize) -> String {
4 let char_count = s.chars().count();
5 if char_count <= max_chars {
6 s.to_string()
7 } else {
8 let truncated: String = s.chars().take(max_chars.saturating_sub(3)).collect();
9 format!("{}...", truncated)
10 }
11}
12
13#[cfg(test)]
14mod tests {
15 use super::*;
16
17 #[test]
18 fn test_truncate_short_string() {
19 assert_eq!(truncate("hello", 10), "hello");
20 }
21
22 #[test]
23 fn test_truncate_exact_length() {
24 assert_eq!(truncate("hello", 5), "hello");
25 }
26
27 #[test]
28 fn test_truncate_long_string() {
29 assert_eq!(truncate("hello world", 8), "hello...");
30 }
31
32 #[test]
33 fn test_truncate_unicode() {
34 assert_eq!(truncate("héllo wörld", 8), "héllo...");
35 }
36
37 #[test]
38 fn test_truncate_emoji() {
39 assert_eq!(truncate("👋🌍🎉🚀🎯", 4), "👋...");
40 }
41
42 #[test]
43 fn test_truncate_empty() {
44 assert_eq!(truncate("", 10), "");
45 }
46
47 #[test]
48 fn test_truncate_zero_max() {
49 assert_eq!(truncate("hello", 0), "...");
50 }
51}