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