• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Helper functions and structures for debugging purpose
2 
3 use nom::combinator::{map, peek, rest};
4 use nom::HexDisplay;
5 use nom::IResult;
6 use std::fmt;
7 
8 /// Dump the remaining bytes to stderr, formatted as hex
dbg_dmp_rest(i: &[u8]) -> IResult<&[u8], ()>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 
13 /// Wrapper for printing value as u8 hex data
14 pub struct HexU8(pub u8);
15 
16 impl fmt::Debug for HexU8 {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result17     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 {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result26     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> {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result35     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]
debug_print_hexu8()46     fn debug_print_hexu8() {
47         assert_eq!(format!("{:?}", debug::HexU8(18)), "0x12");
48     }
49 
50     #[test]
debug_print_hexu16()51     fn debug_print_hexu16() {
52         assert_eq!(format!("{:?}", debug::HexU16(32769)), "0x8001");
53     }
54 
55     #[test]
debug_print_hexslice()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 }
63