1pub fn truncate_string(input: &str, max_chars: usize) -> String {
7 if input.chars().count() > max_chars {
8 if max_chars < 3 {
11 input.chars().take(max_chars).collect::<String>()
12 } else {
13 format!(
15 "{}...",
16 input.chars().take(max_chars - 3).collect::<String>()
17 )
18 }
19 } else {
20 input.to_string()
21 }
22}
23
24#[cfg(test)]
25mod tests {
26 use super::*;
27
28 #[test]
29 fn test_truncate_no_truncation() {
30 assert_eq!(truncate_string("hello", 10), "hello");
31 assert_eq!(truncate_string("hello", 5), "hello");
32 }
33
34 #[test]
35 fn test_truncate_with_truncation() {
36 assert_eq!(truncate_string("hello world", 10), "hello w...");
37 assert_eq!(truncate_string("hello world", 5), "he...");
38 }
39
40 #[test]
41 fn test_truncate_short_limit() {
42 assert_eq!(truncate_string("hello world", 3), "..."); assert_eq!(truncate_string("hello world", 2), "he"); assert_eq!(truncate_string("hello world", 1), "h"); assert_eq!(truncate_string("hello world", 0), ""); }
47
48 #[test]
49 fn test_truncate_unicode() {
50 assert_eq!(truncate_string("你好世界", 10), "你好世界"); assert_eq!(truncate_string("你好世界", 4), "你好世界");
52 assert_eq!(truncate_string("你好世界", 3), "..."); assert_eq!(truncate_string("你好世界", 2), "你好"); }
55
56 #[test]
57 fn test_truncate_empty() {
58 assert_eq!(truncate_string("", 10), "");
59 assert_eq!(truncate_string("", 0), "");
60 }
61}