I’m looking for a way to pretty-print byte strings in error messages, logs and the like.
The closest thing I could find is ascii::escape_default
, but it currently looks like a sore thumb: it does not plug into the infrastructure of Char::escape_default
, and the way to process escaped characters is a mutable closure that accepts bytes.
This is the best I could come up with:
fn escape_bytestring(s: &[u8]) -> String {
let mut acc: Vec<u8> = Vec::with_capacity(s.len());
for &c in s.iter() {
ascii::escape_default(c, |e| {
acc.push(e);
})
}
String::from_utf8(acc).unwrap()
}