mermaid_cli/utils/
text.rs1use crate::constants::WEB_CONTENT_MAX_CHARS;
2
3pub fn truncate_content(content: &str, max_chars: usize) -> String {
5 if content.len() <= max_chars {
8 return content.to_string();
9 }
10
11 if let Some((byte_end, _)) = content.char_indices().nth(max_chars) {
14 format!("{}...[truncated]", &content[..byte_end])
15 } else {
16 content.to_string()
18 }
19}
20
21pub fn truncate_web_content(content: &str) -> String {
23 truncate_content(content, WEB_CONTENT_MAX_CHARS)
24}
25
26pub fn format_duration(total_secs: f64) -> String {
31 let secs = total_secs as u64;
32 if secs < 60 {
33 return format!("{:.1}s", total_secs);
34 }
35 let days = secs / 86400;
36 let hours = (secs % 86400) / 3600;
37 let mins = (secs % 3600) / 60;
38 let remainder = secs % 60;
39 if days > 0 {
40 format!("{}d {}h {}m {}s", days, hours, mins, remainder)
41 } else if hours > 0 {
42 format!("{}h {}m {}s", hours, mins, remainder)
43 } else {
44 format!("{}m {}s", mins, remainder)
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51
52 #[test]
53 fn test_format_duration_sub_minute() {
54 assert_eq!(format_duration(0.0), "0.0s");
55 assert_eq!(format_duration(12.3), "12.3s");
56 assert_eq!(format_duration(59.9), "59.9s");
57 }
58
59 #[test]
60 fn test_format_duration_minutes_and_above() {
61 assert_eq!(format_duration(60.0), "1m 0s");
62 assert_eq!(format_duration(107.0), "1m 47s");
63 assert_eq!(format_duration(3600.0), "1h 0m 0s");
64 assert_eq!(format_duration(86400.0), "1d 0h 0m 0s");
65 assert_eq!(format_duration(90061.0), "1d 1h 1m 1s");
66 }
67
68 #[test]
69 fn test_truncate_content() {
70 let short = "hello";
71 assert_eq!(truncate_content(short, 100), "hello");
72
73 let long = "a".repeat(200);
74 let truncated = truncate_content(&long, 50);
75 assert!(truncated.ends_with("...[truncated]"));
76 assert!(truncated.len() < 200);
77 }
78}