blob: ec8977b1faa1f9da99f7f00fd7ba2d79a6dc68cf [file] [log] [blame]
Yiming Jingebb18722021-07-16 13:15:12 -07001//! Helper functions and structures for debugging purpose
2
Joel Galensondcd5c522021-09-22 11:16:43 -07003use nom::combinator::{map, peek, rest};
4use nom::HexDisplay;
5use nom::IResult;
Yiming Jingebb18722021-07-16 13:15:12 -07006use std::fmt;
7
Joel Galensondcd5c522021-09-22 11:16:43 -07008/// Dump the remaining bytes to stderr, formatted as hex
9pub 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 Jingebb18722021-07-16 13:15:12 -070013/// Wrapper for printing value as u8 hex data
14pub struct HexU8(pub u8);
15
16impl 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
23pub struct HexU16(pub u16);
24
25impl 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
32pub struct HexSlice<'a>(pub &'a [u8]);
33
34impl<'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)]
42mod 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}