Skip to main content

gor/cmd/
util.rs

1//! Shared helpers for command implementations.
2//!
3//! Common utilities for pagination, body building, field selection,
4//! and other cross-cutting concerns used by multiple commands.
5
6/// Truncates a string to `max_len` characters, appending "…" if truncated.
7///
8/// # Examples
9///
10/// ```
11/// use gor::cmd::util::truncate;
12///
13/// assert_eq!(truncate("hello", 10), "hello");
14/// assert_eq!(truncate("hello world", 5), "hello…");
15/// ```
16#[must_use]
17pub fn truncate(s: &str, max_len: usize) -> String {
18    if s.len() <= max_len {
19        s.to_string()
20    } else {
21        let mut truncated = s.chars().take(max_len).collect::<String>();
22        truncated.push('…');
23        truncated
24    }
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30
31    #[test]
32    fn truncate_short_string() {
33        assert_eq!(truncate("hi", 10), "hi");
34    }
35
36    #[test]
37    fn truncate_exact_length() {
38        assert_eq!(truncate("hello", 5), "hello");
39    }
40
41    #[test]
42    fn truncate_long_string() {
43        assert_eq!(truncate("hello world", 5), "hello…");
44    }
45
46    #[test]
47    fn truncate_empty() {
48        assert_eq!(truncate("", 5), "");
49    }
50}