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