Hard-wrap a single line to fit within display width (columns). Preserves all characters (no truncation), splitting long lines into multiple lines.
(s: &str, max_width: usize)
| 79 | /// Hard-wrap a single line to fit within display width (columns). |
| 80 | /// Preserves all characters (no truncation), splitting long lines into multiple lines. |
| 81 | pub fn wrap_to_display_width(s: &str, max_width: usize) -> Vec<String> { |
| 82 | if max_width == 0 { |
| 83 | return vec![String::new()]; |
| 84 | } |
| 85 | if s.is_empty() { |
| 86 | return vec![String::new()]; |
| 87 | } |
| 88 | |
| 89 | let mut lines: Vec<String> = Vec::new(); |
| 90 | let mut current = String::new(); |
| 91 | let mut current_width = 0usize; |
| 92 | |
| 93 | for ch in s.chars() { |
| 94 | let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0); |
| 95 | |
| 96 | if !current.is_empty() && current_width + ch_width > max_width { |
| 97 | lines.push(std::mem::take(&mut current)); |
| 98 | current_width = 0; |
| 99 | } |
| 100 | |
| 101 | current.push(ch); |
| 102 | current_width += ch_width; |
| 103 | |
| 104 | if current_width >= max_width && !current.is_empty() { |
| 105 | lines.push(std::mem::take(&mut current)); |
| 106 | current_width = 0; |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | if !current.is_empty() { |
| 111 | lines.push(current); |
| 112 | } |
| 113 | |
| 114 | if lines.is_empty() { |
| 115 | lines.push(String::new()); |
| 116 | } |
| 117 | |
| 118 | lines |
| 119 | } |
no test coverage detected