Skip to main content

rigspark_cli/
accessible_text.rs

1use regex::Regex;
2use std::{io, sync::OnceLock};
3use unicode_normalization::UnicodeNormalization;
4use unicode_segmentation::UnicodeSegmentation;
5
6fn truncate(value: &str, already_truncated: bool, limit: usize) -> String {
7    if value.len() <= limit && !already_truncated {
8        return value.into();
9    }
10    static ESCAPE: OnceLock<Regex> = OnceLock::new();
11    let escape = ESCAPE
12        .get_or_init(|| Regex::new(r"\\u\{[0-9A-F]+\}").expect("valid visible escape pattern"));
13    let mut units = Vec::new();
14    let mut offset = 0;
15    for token in escape.find_iter(value) {
16        units.extend(value[offset..token.start()].graphemes(true));
17        units.push(token.as_str());
18        offset = token.end();
19    }
20    units.extend(value[offset..].graphemes(true));
21    let mut output = String::new();
22    for unit in units {
23        if output.len() + unit.len() > limit - 3 {
24            break;
25        }
26        output.push_str(unit);
27    }
28    output.push('\u{2026}');
29    output
30}
31
32fn escape(value: &str, action: bool, multiline: bool, limit: usize) -> io::Result<String> {
33    if value.len() > 1024 * 1024 {
34        return Err(io::Error::other("terminal text exceeds 1 MiB"));
35    }
36    static IGNORABLE: OnceLock<Regex> = OnceLock::new();
37    let ignorable = IGNORABLE.get_or_init(|| {
38        Regex::new(r"^\p{Default_Ignorable_Code_Point}$").expect("valid Unicode property")
39    });
40    let mut characters = value.chars().peekable();
41    let mut escaped = String::new();
42    let mut truncated = false;
43    while let Some(character) = characters.next() {
44        let replacement = if action {
45            if character.is_ascii_lowercase()
46                || character.is_ascii_digit()
47                || "._:/-".contains(character)
48            {
49                character.to_string()
50            } else {
51                format!("\\u{{{:X}}}", u32::from(character))
52            }
53        } else {
54            match character {
55                '\r' => {
56                    if characters.peek() == Some(&'\n') {
57                        characters.next();
58                    }
59                    if multiline { "\n" } else { "\\n" }.into()
60                }
61                '\n' => if multiline { "\n" } else { "\\n" }.into(),
62                '\t' => "  ".into(),
63                value
64                    if value.is_control()
65                        || matches!(value, '\u{2028}' | '\u{2029}')
66                        || ignorable.is_match(&value.to_string()) =>
67                {
68                    format!("\\u{{{:X}}}", u32::from(value))
69                }
70                value => value.to_string(),
71            }
72        };
73        if escaped.len() + replacement.len() > limit + 1024 {
74            truncated = true;
75            break;
76        }
77        escaped.push_str(&replacement);
78    }
79    let normalized = if action {
80        escaped
81    } else {
82        escaped.nfc().collect()
83    };
84    Ok(truncate(&normalized, truncated, limit))
85}
86
87pub fn single_line(value: &str) -> io::Result<String> {
88    escape(value, false, false, 256)
89}
90pub fn identifier(value: &str) -> io::Result<String> {
91    escape(value, true, false, 256)
92}
93pub fn multiline(value: &str) -> io::Result<String> {
94    escape(value, false, true, 8192)
95}
96pub fn chat_message(value: &str) -> io::Result<String> {
97    escape(value, false, true, 65536)
98}