rust/utils: Add space mode for HexSlice display

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 <fcallies@linux.ibm.com>
Co-developed-by: Steffen Eiden <seiden@linux.ibm.com>
Reviewed-by: Steffen Eiden <seiden@linux.ibm.com>
Signed-off-by: Jan Höppner <hoeppner@linux.ibm.com>
This commit is contained in:
Finn Callies
2024-09-17 15:36:52 +02:00
committed by Jan Höppner
parent 8da2f44ae2
commit e7cef378e0

View File

@@ -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:-}"));
}