Skip to main content

canic_utils/
format.rs

1//!
2//! Small formatting helpers shared across logs and UI responses.
3//!
4
5///
6/// Truncate a string to at most `max_chars` Unicode scalar values.
7///
8/// Returns the original string when it already fits.
9///
10#[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///
23/// TESTS
24///
25
26#[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}