Skip to main content

glory_render/
text.rs

1use std::borrow::Cow;
2
3/// Canonical editable text: CRLF/CR become LF in multiline controls, line
4/// breaks are removed from single-line host input, and NUL becomes U+FFFD.
5/// Programmatic single-line values must reject line breaks before calling this.
6/// Already canonical text is borrowed without an allocation.
7pub fn normalize_text(value: &str, multiline: bool) -> Cow<'_, str> {
8    if !value.contains(['\r', '\0']) && (multiline || !value.contains('\n')) {
9        return Cow::Borrowed(value);
10    }
11    let mut output = String::with_capacity(value.len());
12    let mut chars = value.chars().peekable();
13    while let Some(ch) = chars.next() {
14        match ch {
15            '\r' if multiline => {
16                if chars.peek() == Some(&'\n') {
17                    chars.next();
18                }
19                output.push('\n');
20            }
21            '\r' | '\n' if !multiline => {}
22            '\0' => output.push('\u{fffd}'),
23            ch => output.push(ch),
24        }
25    }
26    Cow::Owned(output)
27}