1#[must_use]
11pub fn truncate(s: &str, max_chars: usize) -> String {
12 let mut chars = s.chars();
13 let truncated: String = chars.by_ref().take(max_chars).collect();
14
15 if chars.next().is_some() {
16 truncated
17 } else {
18 s.to_string()
19 }
20}
21
22#[cfg(test)]
27mod tests {
28 use super::truncate;
29
30 #[test]
31 fn keeps_short_strings() {
32 assert_eq!(truncate("root", 9), "root");
33 assert_eq!(truncate("abcdefgh", 9), "abcdefgh");
34 assert_eq!(truncate("abcdefghi", 9), "abcdefghi");
35 }
36
37 #[test]
38 fn truncates_long_strings() {
39 assert_eq!(truncate("abcdefghijkl", 9), "abcdefghi");
40 assert_eq!(truncate("abcdefghijklmnopqrstuvwxyz", 9), "abcdefghi");
41 }
42}