From 851d3efd666b239f61a1a75d31cb7b91b78cf2b5 Mon Sep 17 00:00:00 2001 From: Pavel Grigorenko Date: Mon, 5 Aug 2024 18:02:46 +0300 Subject: [PATCH] fix(aya-log): print &[u8] using full width --- aya-log/src/lib.rs | 56 +++++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 16 deletions(-) diff --git a/aya-log/src/lib.rs b/aya-log/src/lib.rs index 9dcbb2f5..e09a9fea 100644 --- a/aya-log/src/lib.rs +++ b/aya-log/src/lib.rs @@ -204,15 +204,12 @@ where } } -pub struct LowerHexDebugFormatter; -impl Formatter<&[T]> for LowerHexDebugFormatter -where - T: LowerHex, -{ - fn format(v: &[T]) -> String { +pub struct LowerHexBytesFormatter; +impl Formatter<&[u8]> for LowerHexBytesFormatter { + fn format(v: &[u8]) -> String { let mut s = String::new(); for v in v { - let () = core::fmt::write(&mut s, format_args!("{v:x}")).unwrap(); + let () = core::fmt::write(&mut s, format_args!("{v:02x}")).unwrap(); } s } @@ -228,15 +225,12 @@ where } } -pub struct UpperHexDebugFormatter; -impl Formatter<&[T]> for UpperHexDebugFormatter -where - T: UpperHex, -{ - fn format(v: &[T]) -> String { +pub struct UpperHexBytesFormatter; +impl Formatter<&[u8]> for UpperHexBytesFormatter { + fn format(v: &[u8]) -> String { let mut s = String::new(); for v in v { - let () = core::fmt::write(&mut s, format_args!("{v:X}")).unwrap(); + let () = core::fmt::write(&mut s, format_args!("{v:02X}")).unwrap(); } s } @@ -289,8 +283,8 @@ trait Format { impl Format for &[u8] { fn format(&self, last_hint: Option) -> Result { match last_hint.map(|DisplayHintWrapper(dh)| dh) { - Some(DisplayHint::LowerHex) => Ok(LowerHexDebugFormatter::format(self)), - Some(DisplayHint::UpperHex) => Ok(UpperHexDebugFormatter::format(self)), + Some(DisplayHint::LowerHex) => Ok(LowerHexBytesFormatter::format(self)), + Some(DisplayHint::UpperHex) => Ok(UpperHexBytesFormatter::format(self)), _ => Err(()), } } @@ -781,6 +775,36 @@ mod test { }); } + #[test] + fn test_bytes_unambiguous() { + testing_logger::setup(); + let (mut len, mut input) = new_log(5).unwrap(); + + len += DisplayHint::LowerHex + .write(&mut input[len..]) + .unwrap() + .get(); + len += [0x01, 0x02].write(&mut input[len..]).unwrap().get(); + + len += " ".write(&mut input[len..]).unwrap().get(); + + len += DisplayHint::LowerHex + .write(&mut input[len..]) + .unwrap() + .get(); + len += [0x12].write(&mut input[len..]).unwrap().get(); + + _ = len; + + let logger = logger(); + let () = log_buf(&input, logger).unwrap(); + testing_logger::validate(|captured_logs| { + assert_eq!(captured_logs.len(), 1); + assert_eq!(captured_logs[0].body, "0102 12"); + assert_eq!(captured_logs[0].level, Level::Info); + }); + } + #[test] fn test_display_hint_default() { testing_logger::setup();