Skip to main content

radio_cli/
lib.rs

1mod artwork;
2pub mod cli;
3pub mod config;
4pub mod directory;
5pub mod engine;
6pub mod error;
7pub mod messages;
8pub mod model;
9pub mod player;
10pub mod process;
11pub mod recorder;
12mod redact;
13pub mod service;
14pub mod speech;
15pub mod store;
16mod territories;
17pub mod tui;
18
19use unicode_segmentation::UnicodeSegmentation;
20pub const USER_AGENT: &str = concat!("radio-cli/", env!("CARGO_PKG_VERSION"));
21
22const CLEAN_TEXT_LIMIT: usize = 1024;
23
24/// External text must never introduce terminal escape sequences or new lines.
25///
26/// The length limit counts scalar values but never cuts through a grapheme
27/// cluster, so a joiner or combining mark is not left dangling at the end.
28pub fn clean_text(text: &str) -> String {
29    let mut cleaned = String::new();
30    let mut count = 0;
31    for grapheme in text.graphemes(true) {
32        // Control characters always form their own cluster, including CR LF.
33        if grapheme.chars().next().is_none_or(char::is_control) {
34            continue;
35        }
36        count += grapheme.chars().count();
37        if count > CLEAN_TEXT_LIMIT {
38            break;
39        }
40        cleaned.push_str(grapheme);
41    }
42    cleaned
43}
44
45#[cfg(test)]
46mod clean_text_tests {
47    use super::*;
48
49    #[test]
50    fn clean_text_strips_controls_and_caps_on_a_grapheme_boundary() {
51        assert_eq!(clean_text("a\u{1b}[31mb\r\nc\u{7f}"), "a[31mbc");
52        assert_eq!(clean_text("你好 ✓"), "你好 ✓");
53        let long = "x".repeat(CLEAN_TEXT_LIMIT + 10);
54        assert_eq!(clean_text(&long).chars().count(), CLEAN_TEXT_LIMIT);
55
56        // The cluster is five scalar values and would cross the limit: drop it whole.
57        let family = "👨\u{200d}👩\u{200d}👧";
58        let text = format!("{}{family}tail", "x".repeat(CLEAN_TEXT_LIMIT - 2));
59        assert_eq!(clean_text(&text), "x".repeat(CLEAN_TEXT_LIMIT - 2));
60
61        // Exactly at the limit the cluster is kept intact.
62        let text = format!("{}{family}tail", "x".repeat(CLEAN_TEXT_LIMIT - 5));
63        assert_eq!(
64            clean_text(&text),
65            format!("{}{family}", "x".repeat(CLEAN_TEXT_LIMIT - 5))
66        );
67
68        let accents = format!("e{}", "\u{301}".repeat(CLEAN_TEXT_LIMIT));
69        assert_eq!(clean_text(&accents), "");
70    }
71}
72
73#[cfg(test)]
74extern crate self as radio_cli;
75#[cfg(test)]
76#[path = "../tests/support/mod.rs"]
77mod test_support;