pub(crate) fn normalize_message(value: impl Into<String>, max_bytes: usize) -> Option<String> {
let value = value.into();
let mut normalized = String::with_capacity(value.len().min(max_bytes));
let mut pending_space = false;
for character in value.chars() {
if character.is_control() || character.is_whitespace() {
pending_space = !normalized.is_empty();
continue;
}
if normalized.len() + usize::from(pending_space) + character.len_utf8() > max_bytes {
break;
}
if pending_space {
normalized.push(' ');
}
normalized.push(character);
pending_space = false;
}
(!normalized.is_empty()).then_some(normalized)
}