#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WrappedLine {
pub text: String,
pub start: usize,
}
pub fn wrap(text: &str, max_w: f32, measure: impl Fn(&str) -> f32) -> Vec<WrappedLine> {
let wrap_enabled = max_w.is_finite() && max_w > 0.0;
let mut out = Vec::new();
let mut para_start = 0usize;
for para in text.split('\n') {
let para_end = para_start + para.len();
if !wrap_enabled {
out.push(WrappedLine {
text: para.trim_end().to_string(),
start: para_start,
});
} else {
wrap_paragraph(para, para_start, max_w, &measure, &mut out);
}
para_start = para_end + 1; }
if out.is_empty() {
out.push(WrappedLine {
text: String::new(),
start: 0,
});
}
out
}
fn wrap_paragraph(
para: &str,
base: usize,
max_w: f32,
measure: &impl Fn(&str) -> f32,
out: &mut Vec<WrappedLine>,
) {
let mut line_start = 0usize; let mut last_break: Option<usize> = None; let mut cur_end = 0usize;
let chars: Vec<(usize, char)> = para.char_indices().collect();
let mut i = 0usize;
while i < chars.len() {
let (offset, ch) = chars[i];
let next_offset = offset + ch.len_utf8();
let candidate = ¶[line_start..next_offset];
if measure(candidate.trim_end()) <= max_w || candidate.trim_end().is_empty() {
if ch == ' ' {
last_break = Some(next_offset);
}
cur_end = next_offset;
i += 1;
continue;
}
let cut = match last_break {
Some(b) if b > line_start => b,
_ if cur_end > line_start => cur_end,
_ => next_offset,
};
out.push(WrappedLine {
text: para[line_start..cut].trim_end().to_string(),
start: base + line_start,
});
line_start = cut;
while line_start < para.len() && para[line_start..].starts_with(' ') {
line_start += 1;
}
last_break = None;
cur_end = line_start;
while i < chars.len() && chars[i].0 < line_start {
i += 1;
}
}
if line_start < para.len() {
out.push(WrappedLine {
text: para[line_start..].trim_end().to_string(),
start: base + line_start,
});
} else if para.is_empty() {
out.push(WrappedLine {
text: String::new(),
start: base,
});
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mono(s: &str) -> f32 {
s.chars().count() as f32 * 10.0
}
fn texts(lines: &[WrappedLine]) -> Vec<&str> {
lines.iter().map(|l| l.text.as_str()).collect()
}
#[test]
fn short_text_stays_on_one_line() {
let out = wrap("hello", 100.0, mono);
assert_eq!(texts(&out), vec!["hello"]);
assert_eq!(out[0].start, 0);
}
#[test]
fn wraps_at_spaces_and_never_splits_a_word() {
let out = wrap("aaaaa bbbbb ccccc", 60.0, mono);
assert_eq!(texts(&out), vec!["aaaaa", "bbbbb", "ccccc"]);
assert_eq!(out[1].start, 6);
assert_eq!(out[2].start, 12);
}
#[test]
fn trailing_spaces_are_trimmed_from_wrapped_lines() {
let out = wrap("aa bb", 50.0, mono);
for l in &out {
assert!(!l.text.ends_with(' '), "行尾不该留下空格:{l:?}");
}
}
#[test]
fn cjk_without_spaces_breaks_by_character() {
let out = wrap("中文折行测试", 30.0, mono);
assert_eq!(texts(&out), vec!["中文折", "行测试"]);
}
#[test]
fn explicit_newlines_are_preserved() {
let out = wrap("ab\ncd", 100.0, mono);
assert_eq!(texts(&out), vec!["ab", "cd"]);
assert_eq!(out[1].start, 3);
}
#[test]
fn non_positive_or_infinite_width_disables_wrapping() {
let long = "aaaaaaaaaa bbbbbbbbbb";
assert_eq!(texts(&wrap(long, 0.0, mono)), vec![long]);
assert_eq!(texts(&wrap(long, -5.0, mono)), vec![long]);
assert_eq!(texts(&wrap(long, f32::INFINITY, mono)), vec![long]);
assert_eq!(texts(&wrap(long, f32::NAN, mono)), vec![long]);
}
#[test]
fn single_char_wider_than_the_line_still_gets_its_own_line() {
let out = wrap("abc", 5.0, mono);
assert_eq!(texts(&out), vec!["a", "b", "c"]);
}
#[test]
fn empty_text_yields_one_empty_line() {
let out = wrap("", 50.0, mono);
assert_eq!(out.len(), 1);
assert_eq!(out[0].text, "");
}
#[test]
fn text_that_exactly_fits_is_not_wrapped() {
let out = wrap("abcdefghij", 100.0, mono);
assert_eq!(out.len(), 1);
}
#[test]
fn wrapping_is_lossless_except_for_collapsed_spaces() {
let src = "alpha beta gamma delta";
let out = wrap(src, 60.0, mono);
let joined: String = out
.iter()
.map(|l| l.text.as_str())
.collect::<Vec<_>>()
.join(" ");
let strip = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
assert_eq!(strip(&joined), strip(src));
}
}