Yiming Jing | ebb1872 | 2021-07-16 13:15:12 -0700 | [diff] [blame] | 1 | //! Helper functions and structures for debugging purpose |
| 2 | |
Joel Galenson | dcd5c52 | 2021-09-22 11:16:43 -0700 | [diff] [blame] | 3 | use nom::combinator::{map, peek, rest}; |
| 4 | use nom::HexDisplay; |
| 5 | use nom::IResult; |
Yiming Jing | ebb1872 | 2021-07-16 13:15:12 -0700 | [diff] [blame] | 6 | use std::fmt; |
| 7 | |
Joel Galenson | dcd5c52 | 2021-09-22 11:16:43 -0700 | [diff] [blame] | 8 | /// Dump the remaining bytes to stderr, formatted as hex |
| 9 | pub fn dbg_dmp_rest(i: &[u8]) -> IResult<&[u8], ()> { |
| 10 | map(peek(rest), |r: &[u8]| eprintln!("\n{}\n", r.to_hex(16)))(i) |
| 11 | } |
| 12 | |
Yiming Jing | ebb1872 | 2021-07-16 13:15:12 -0700 | [diff] [blame] | 13 | /// Wrapper for printing value as u8 hex data |
| 14 | pub struct HexU8(pub u8); |
| 15 | |
| 16 | impl fmt::Debug for HexU8 { |
| 17 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 18 | write!(fmt, "0x{:02x}", self.0) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | /// Wrapper for printing value as u16 hex data |
| 23 | pub struct HexU16(pub u16); |
| 24 | |
| 25 | impl fmt::Debug for HexU16 { |
| 26 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 27 | write!(fmt, "0x{:04x}", self.0) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /// Wrapper for printing slice as hex data |
| 32 | pub struct HexSlice<'a>(pub &'a [u8]); |
| 33 | |
| 34 | impl<'a> fmt::Debug for HexSlice<'a> { |
| 35 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 36 | let s: Vec<_> = self.0.iter().map(|&i| format!("{:02x}", i)).collect(); |
| 37 | write!(fmt, "[{}]", s.join(" ")) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | #[cfg(test)] |
| 42 | mod tests { |
| 43 | use crate::debug; |
| 44 | |
| 45 | #[test] |
| 46 | fn debug_print_hexu8() { |
| 47 | assert_eq!(format!("{:?}", debug::HexU8(18)), "0x12"); |
| 48 | } |
| 49 | |
| 50 | #[test] |
| 51 | fn debug_print_hexu16() { |
| 52 | assert_eq!(format!("{:?}", debug::HexU16(32769)), "0x8001"); |
| 53 | } |
| 54 | |
| 55 | #[test] |
| 56 | fn debug_print_hexslice() { |
| 57 | assert_eq!( |
| 58 | format!("{:?}", debug::HexSlice(&[15, 16, 17, 18, 19, 20])), |
| 59 | "[0f 10 11 12 13 14]" |
| 60 | ); |
| 61 | } |
| 62 | } |