Skip to main content

volition_core/
utils.rs

1// volition-agent-core/src/utils.rs
2//! General utility functions.
3
4/// Truncates a string to a maximum character count, adding an ellipsis if truncated.
5/// Handles multi-byte characters correctly.
6pub fn truncate_string(input: &str, max_chars: usize) -> String {
7    if input.chars().count() > max_chars {
8        // If the limit is too small to include any characters plus "...",
9        // just take the first max_chars characters without an ellipsis.
10        if max_chars < 3 {
11            input.chars().take(max_chars).collect::<String>()
12        } else {
13            // Otherwise, take max_chars - 3 characters and add "..."
14            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), "..."); // Correct: 0 chars + ...
43        assert_eq!(truncate_string("hello world", 2), "he"); // Correct: 2 chars, no ...
44        assert_eq!(truncate_string("hello world", 1), "h"); // Correct: 1 char, no ...
45        assert_eq!(truncate_string("hello world", 0), ""); // Correct: 0 chars, no ...
46    }
47
48    #[test]
49    fn test_truncate_unicode() {
50        assert_eq!(truncate_string("你好世界", 10), "你好世界"); // 4 chars
51        assert_eq!(truncate_string("你好世界", 4), "你好世界");
52        assert_eq!(truncate_string("你好世界", 3), "..."); // Corrected assertion: 0 chars + ...
53        assert_eq!(truncate_string("你好世界", 2), "你好"); // Correct: 2 chars, no ...
54    }
55
56    #[test]
57    fn test_truncate_empty() {
58        assert_eq!(truncate_string("", 10), "");
59        assert_eq!(truncate_string("", 0), "");
60    }
61}