You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.8 KiB
Rust

//! Utility helpers for claudbg.
/// Returns the first 8 characters of a session/agent ID for compact display.
///
/// If the ID is shorter than 8 characters, returns the full ID.
pub fn short_id(id: &str) -> &str {
&id[..id.len().min(8)]
}
/// Escapes special XML characters in a string for safe embedding in XML content.
///
/// The following substitutions are applied:
/// - `&` → `&`
/// - `<` → `&lt;`
/// - `>` → `&gt;`
/// - `"` → `&quot;`
/// - `'` → `&apos;`
pub fn xml_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
other => out.push(other),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// `short_id` returns the first 8 characters of a 36-character UUID.
#[test]
fn short_id_uuid() {
let uuid = "550e8400-e29b-41d4-a716-446655440000";
assert_eq!(short_id(uuid), "550e8400");
}
/// `short_id` returns the full string when it is shorter than 8 characters.
#[test]
fn short_id_short_string() {
assert_eq!(short_id("abc"), "abc");
}
/// `short_id` returns an empty string for an empty input.
#[test]
fn short_id_empty_string() {
assert_eq!(short_id(""), "");
}
/// `short_id` returns exactly 8 characters when input is exactly 8 characters.
#[test]
fn short_id_exact_length() {
assert_eq!(short_id("12345678"), "12345678");
}
/// `xml_escape` replaces `&` with `&amp;`.
#[test]
fn xml_escape_ampersand() {
assert_eq!(xml_escape("a & b"), "a &amp; b");
}
/// `xml_escape` replaces `<` with `&lt;` and `>` with `&gt;`.
#[test]
fn xml_escape_angle_brackets() {
assert_eq!(xml_escape("<tag>"), "&lt;tag&gt;");
}
/// `xml_escape` replaces `"` with `&quot;`.
#[test]
fn xml_escape_double_quote() {
assert_eq!(xml_escape(r#"say "hello""#), "say &quot;hello&quot;");
}
/// `xml_escape` replaces `'` with `&apos;`.
#[test]
fn xml_escape_single_quote() {
assert_eq!(xml_escape("it's"), "it&apos;s");
}
/// `xml_escape` handles a string with multiple special characters.
#[test]
fn xml_escape_multiple() {
assert_eq!(
xml_escape(r#"<a href="x&y">it's</a>"#),
"&lt;a href=&quot;x&amp;y&quot;&gt;it&apos;s&lt;/a&gt;"
);
}
/// `xml_escape` returns the input unchanged if no special characters are present.
#[test]
fn xml_escape_no_special() {
assert_eq!(xml_escape("hello world"), "hello world");
}
}