use unicode_general_category::{get_general_category, GeneralCategory};
pub const MAX_LOG_FIELD: usize = 200;
fn printable(ch: char) -> bool {
if ch == ' ' {
return true;
}
!matches!(
get_general_category(ch),
GeneralCategory::Control
| GeneralCategory::Format
| GeneralCategory::Surrogate
| GeneralCategory::PrivateUse
| GeneralCategory::Unassigned
| GeneralCategory::LineSeparator
| GeneralCategory::ParagraphSeparator
| GeneralCategory::SpaceSeparator
)
}
fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
match ch {
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
_ if printable(ch) => out.push(ch),
_ => {
let code = ch as u32;
if code <= 0xFF {
out.push_str(&format!("\\x{code:02x}"));
} else {
out.push_str(&format!("\\u{code:04x}"));
}
}
}
}
out
}
pub fn log_value(value: &str) -> String {
log_value_with_limit(value, MAX_LOG_FIELD)
}
pub fn log_value_with_limit(value: &str, max_length: usize) -> String {
let encoded = escape(value);
if encoded.chars().count() <= max_length {
return encoded;
}
if max_length <= 3 {
return "...".to_string();
}
let mut truncated: String = encoded.chars().take(max_length - 3).collect();
truncated.push_str("...");
truncated
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_line_breaks_tabs_and_control_characters() {
assert_eq!(log_value("a\nb\rc\td"), "a\\nb\\rc\\td");
assert_eq!(log_value("\u{1b}[31mred"), "\\x1b[31mred");
assert_eq!(log_value("a\u{2028}b\u{2029}c"), "a\\u2028b\\u2029c");
assert_eq!(log_value("a\u{200b}b"), "a\\u200bb");
}
#[test]
fn keeps_backslashes_and_visible_text() {
assert_eq!(log_value("C:\\reports\\a.pdf"), "C:\\reports\\a.pdf");
assert_eq!(log_value("São Paulo"), "São Paulo");
}
#[test]
fn truncates_with_an_ellipsis() {
assert_eq!(log_value_with_limit("abcdef", 5), "ab...");
assert_eq!(log_value_with_limit("abc", 5), "abc");
assert_eq!(log_value_with_limit("abcdef", 3), "...");
}
#[test]
fn never_emits_a_raw_line_break() {
let encoded = log_value("host\nWARN forged\r\tline");
assert!(!encoded.contains('\n'));
assert!(!encoded.contains('\r'));
assert!(!encoded.contains('\t'));
}
}