From 541e8e49d9925c12bf36daa32fd511f5540bb1c6 Mon Sep 17 00:00:00 2001 From: diogo464 Date: Fri, 8 Aug 2025 15:43:04 +0100 Subject: added display() and HexDisplay --- src/lib.rs | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 36790b7..ca878a4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,9 +3,11 @@ //! # Examples //!``` //!let hex_string = "1a2b3c"; -//!let data = rhex::decode_hex(&hex_string).unwrap(); +//!let data = hex::decode_hex(&hex_string).unwrap(); //!``` +use std::fmt::Write; + #[derive(Debug)] ///Possible errors that occur during decoding pub enum HexDecodeError { @@ -119,7 +121,7 @@ fn append_byte_hex_to_string(byte: u8, string: &mut String) { /// ///``` ///let hex_string = "12ffbc"; -///for byte in rhex::decode_hex_iter(&hex_string) { +///for byte in hex::decode_hex_iter(&hex_string) { /// //do something ///} ///``` @@ -135,7 +137,7 @@ where /// ///``` ///let data = &[0x11, 0xbc, 0x22]; -///for c in rhex::encode_hex_iter(&data) { +///for c in hex::encode_hex_iter(&data) { /// //do something with c ///} ///``` @@ -150,7 +152,7 @@ where /// ///``` ///let hex_string = "ffaa11"; -///let data = rhex::decode_hex(&hex_string).unwrap(); +///let data = hex::decode_hex(&hex_string).unwrap(); ///``` pub fn decode_hex>(string: T) -> Result, HexDecodeError> { let chars = string.as_ref(); @@ -175,7 +177,7 @@ pub fn decode_hex>(string: T) -> Result, HexDecodeError> /// ///``` ///let data = &[0x11, 0x12, 0x13]; -///let string = rhex::encode_hex(&data); +///let string = hex::encode_hex(&data); ///assert_eq!(string, "111213"); ///``` pub fn encode_hex>(data: T) -> String { @@ -187,6 +189,24 @@ pub fn encode_hex>(data: T) -> String { string } +pub struct HexDisplay(T); + +impl std::fmt::Display for HexDisplay +where + T: AsRef<[u8]>, +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + for c in encode_hex_iter(self.0.as_ref()) { + f.write_char(c)?; + } + Ok(()) + } +} + +pub fn display>(data: T) -> impl std::fmt::Display { + HexDisplay(data) +} + #[cfg(test)] mod tests { use super::*; @@ -274,4 +294,11 @@ mod tests { let string: String = encode_hex_iter(&data).collect(); assert_eq!(string, "ffaa1245"); } + + #[test] + fn hex_display() { + let data: &[u8; 5] = &[0x01, 0x10, 0xFA, 0x4A, 0x00]; + let string = display(data).to_string(); + assert_eq!(string, "0110fa4a00"); + } } -- cgit