blob: eb4e821da0a016d26ae57512e0f02195ce3822de [file] [log] [blame]
Yiming Jingebb18722021-07-16 13:15:12 -07001//! Helper functions and structures for debugging purpose
2
3use std::fmt;
4
5/// Wrapper for printing value as u8 hex data
6pub struct HexU8(pub u8);
7
8impl fmt::Debug for HexU8 {
9 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
10 write!(fmt, "0x{:02x}", self.0)
11 }
12}
13
14/// Wrapper for printing value as u16 hex data
15pub struct HexU16(pub u16);
16
17impl fmt::Debug for HexU16 {
18 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
19 write!(fmt, "0x{:04x}", self.0)
20 }
21}
22
23/// Wrapper for printing slice as hex data
24pub struct HexSlice<'a>(pub &'a [u8]);
25
26impl<'a> fmt::Debug for HexSlice<'a> {
27 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
28 let s: Vec<_> = self.0.iter().map(|&i| format!("{:02x}", i)).collect();
29 write!(fmt, "[{}]", s.join(" "))
30 }
31}
32
33#[cfg(test)]
34mod tests {
35 use crate::debug;
36
37 #[test]
38 fn debug_print_hexu8() {
39 assert_eq!(format!("{:?}", debug::HexU8(18)), "0x12");
40 }
41
42 #[test]
43 fn debug_print_hexu16() {
44 assert_eq!(format!("{:?}", debug::HexU16(32769)), "0x8001");
45 }
46
47 #[test]
48 fn debug_print_hexslice() {
49 assert_eq!(
50 format!("{:?}", debug::HexSlice(&[15, 16, 17, 18, 19, 20])),
51 "[0f 10 11 12 13 14]"
52 );
53 }
54}