From e7cef378e0d5cbd3de8474a0f227a32a045a7b83 Mon Sep 17 00:00:00 2001 From: Finn Callies Date: Tue, 17 Sep 2024 15:36:52 +0200 Subject: [PATCH] rust/utils: Add space mode for HexSlice display MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a new format option to HexSlice to print every byte with a separated space in between. Additionally the old format option 'alternate' together with the new one results in another new format which prints every byte separated by a space AND every byte has a leading '0x'. Signed-off-by: Finn Callies Co-developed-by: Steffen Eiden Reviewed-by: Steffen Eiden Signed-off-by: Jan Höppner --- rust/utils/src/hexslice.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/rust/utils/src/hexslice.rs b/rust/utils/src/hexslice.rs index 58b60f82..9986160c 100644 --- a/rust/utils/src/hexslice.rs +++ b/rust/utils/src/hexslice.rs @@ -38,11 +38,17 @@ impl<'a> Serialize for HexSlice<'a> { impl std::fmt::Display for HexSlice<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - if f.alternate() { + if f.alternate() && !f.sign_minus() { write!(f, "0x")?; } for byte in self.0 { + if f.sign_minus() && f.alternate() { + write!(f, "0x")?; + } write!(f, "{:0>2x}", byte)?; + if f.sign_minus() { + write!(f, " ")?; + } } Ok(()) } @@ -53,3 +59,11 @@ impl AsRef<[u8]> for HexSlice<'_> { self.0 } } + +#[test] +fn display() { + let hex = HexSlice::from(&[0; 8]); + let exp = "00 00 00 00 00 00 00 00 "; + + assert_eq!(exp, format!("{hex:-}")); +}