rusticata_macros/
debug.rs

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