Safely truncate string to specified byte length
(s: &str, max_bytes: usize)
| 3 | |
| 4 | /// Safely truncate string to specified byte length |
| 5 | pub fn truncate_str(s: &str, max_bytes: usize) -> String { |
| 6 | let first_line = s.lines().next().unwrap_or(""); |
| 7 | |
| 8 | if first_line.len() <= max_bytes { |
| 9 | return first_line.to_string(); |
| 10 | } |
| 11 | |
| 12 | let mut boundary = max_bytes; |
| 13 | while boundary > 0 && !first_line.is_char_boundary(boundary) { |
| 14 | boundary -= 1; |
| 15 | } |
| 16 | |
| 17 | if boundary == 0 { |
| 18 | return String::new(); |
| 19 | } |
| 20 | |
| 21 | format!("{}...", &first_line[..boundary]) |
| 22 | } |
| 23 | |
| 24 | /// Strip ANSI escape sequences from a string. |
| 25 | /// Handles CSI sequences (\x1b[...X), OSC sequences (\x1b]...ST), and simple two-byte escapes. |
no test coverage detected