canic_utils/
format.rs

1//!
2//! Small formatting helpers shared across logs and UI responses.
3//!
4
5///
6/// Ellipsize a string in the middle when it exceeds the `threshold`.
7///
8/// Produces: first `head` chars, a Unicode ellipsis '…', then last `tail` chars.
9/// Returns the original string if it does not exceed the threshold, or if the
10/// requested head/tail slice would not shorten it.
11///
12#[must_use]
13pub fn ellipsize_middle(s: &str, threshold: usize, head: usize, tail: usize) -> String {
14    let len = s.chars().count();
15    // Only ellipsize if strictly longer than threshold and we have space to shorten.
16    if len > threshold && head + 1 + tail < len {
17        let mut it = s.chars();
18        let prefix: String = it.by_ref().take(head).collect();
19        let suffix: String = s
20            .chars()
21            .rev()
22            .take(tail)
23            .collect::<String>()
24            .chars()
25            .rev()
26            .collect();
27
28        format!("{prefix}…{suffix}")
29    } else {
30        s.to_string()
31    }
32}
33
34///
35/// TESTS
36///
37
38#[cfg(test)]
39mod tests {
40    use super::ellipsize_middle;
41
42    #[test]
43    fn keeps_short_strings() {
44        assert_eq!(ellipsize_middle("root", 9, 4, 4), "root");
45        assert_eq!(ellipsize_middle("abcdefgh", 9, 4, 4), "abcdefgh");
46        assert_eq!(ellipsize_middle("abcdefghi", 9, 4, 4), "abcdefghi");
47    }
48
49    #[test]
50    fn ellipsizes_long_strings() {
51        assert_eq!(ellipsize_middle("abcdefghijkl", 9, 4, 4), "abcd…ijkl");
52        assert_eq!(
53            ellipsize_middle("abcdefghijklmnopqrstuvwxyz", 9, 4, 4),
54            "abcd…wxyz"
55        );
56    }
57}