scolapasta_string_escape/
string.rsuse core::fmt::{self, Write};
use crate::literal::{ascii_char_with_escape, Literal};
pub fn format_debug_escape_into<W, T>(mut dest: W, message: T) -> fmt::Result
where
W: Write,
T: AsRef<[u8]>,
{
let mut buf = [0; 4];
let mut message = message.as_ref();
while !message.is_empty() {
let (ch, size) = bstr::decode_utf8(message);
match ch.map(|ch| ascii_char_with_escape(ch).ok_or(ch)) {
Some(Ok(escaped)) => {
dest.write_str(escaped)?;
}
Some(Err(ch)) => {
let enc = ch.encode_utf8(&mut buf);
dest.write_str(enc)?;
}
None => {
for &byte in &message[..size] {
let escaped = Literal::debug_escape(byte);
dest.write_str(escaped)?;
}
}
}
message = &message[size..];
}
Ok(())
}
#[cfg(test)]
mod tests {
use alloc::string::{String, ToString};
use super::format_debug_escape_into;
#[test]
fn format_ascii_message() {
let message = "Spinoso Exception";
let mut dest = String::new();
format_debug_escape_into(&mut dest, message).unwrap();
assert_eq!(dest, "Spinoso Exception");
}
#[test]
fn format_unicode_message() {
let message = "Spinoso Exception 💎🦀";
let mut dest = String::new();
format_debug_escape_into(&mut dest, message).unwrap();
assert_eq!(dest, "Spinoso Exception 💎🦀");
}
#[test]
fn format_invalid_utf8_message() {
let message = b"oh no! \xFF";
let mut dest = String::new();
format_debug_escape_into(&mut dest, message).unwrap();
assert_eq!(dest, r"oh no! \xFF");
}
#[test]
fn format_escape_code_message() {
let message = "yes to symbolic \t\n\x7F";
let mut dest = String::new();
format_debug_escape_into(&mut dest, message).unwrap();
assert_eq!(dest, r"yes to symbolic \t\n\x7F");
}
#[test]
fn replacement_character() {
let message = "This is the replacement character: \u{FFFD}";
let mut dest = String::new();
format_debug_escape_into(&mut dest, message).unwrap();
assert_eq!(dest, "This is the replacement character: \u{FFFD}");
}
#[test]
fn as_ref() {
let message = b"Danger".to_vec();
let mut dest = String::new();
format_debug_escape_into(&mut dest, message).unwrap();
assert_eq!(dest, "Danger");
let message = "Danger".to_string();
let mut dest = String::new();
format_debug_escape_into(&mut dest, message).unwrap();
assert_eq!(dest, "Danger");
}
}