Skip to main content

chainlink/
utils.rs

1/// Format a display ID for output.
2pub fn format_issue_id(id: i64) -> String {
3    format!("#{}", id)
4}
5
6/// Truncate a string to a maximum number of characters, adding "..." if truncated.
7/// Handles Unicode correctly by counting characters, not bytes.
8pub fn truncate(s: &str, max_chars: usize) -> String {
9    let char_count = s.chars().count();
10    if char_count <= max_chars {
11        s.to_string()
12    } else {
13        let truncated: String = s.chars().take(max_chars.saturating_sub(3)).collect();
14        format!("{}...", truncated)
15    }
16}
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21
22    #[test]
23    fn test_truncate_short_string() {
24        assert_eq!(truncate("hello", 10), "hello");
25    }
26
27    #[test]
28    fn test_truncate_exact_length() {
29        assert_eq!(truncate("hello", 5), "hello");
30    }
31
32    #[test]
33    fn test_truncate_long_string() {
34        assert_eq!(truncate("hello world", 8), "hello...");
35    }
36
37    #[test]
38    fn test_truncate_unicode() {
39        assert_eq!(truncate("héllo wörld", 8), "héllo...");
40    }
41
42    #[test]
43    fn test_truncate_emoji() {
44        assert_eq!(truncate("👋🌍🎉🚀🎯", 4), "👋...");
45    }
46
47    #[test]
48    fn test_truncate_empty() {
49        assert_eq!(truncate("", 10), "");
50    }
51
52    #[test]
53    fn test_truncate_zero_max() {
54        assert_eq!(truncate("hello", 0), "...");
55    }
56}