1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! Helper functions and structures for debugging purpose

use std::fmt;

/// Wrapper for printing valut as u8 hex data
pub struct HexU8 {
    /// Encapsulated data
    pub d: u8
}
impl fmt::Debug for HexU8 {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt,"0x{:02x}",self.d)
    }
}

/// Wrapper for printing value as u16 hex data
pub struct HexU16 {
    /// Encapsulated data
    pub d: u16
}
impl fmt::Debug for HexU16 {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt,"0x{:04x}",self.d)
    }
}

/// Wrapper for printing slice as hex data
pub struct HexSlice<'a> {
    /// Encapsulated data
    pub d: &'a[u8]
}
impl<'a> fmt::Debug for HexSlice<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let s : Vec<_> = self.d.iter().map(|&i|{
            format!("{:02x}", i)
        }).collect();
        write!(fmt,"[{}]",s.join(" "))
    }
}







#[cfg(test)]
mod tests {
    use debug;

#[test]
fn debug_print_hexu8() {
    assert_eq!(format!("{:?}", debug::HexU8{d:18}), "0x12");
}

#[test]
fn debug_print_hexu16() {
    assert_eq!(format!("{:?}", debug::HexU16{d:32769}), "0x8001");
}

#[test]
fn debug_print_hexslice() {
    assert_eq!(format!("{:?}", debug::HexSlice{d:&[15, 16, 17, 18, 19, 20]}), "[0f 10 11 12 13 14]");
}

}