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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// SPDX-License-Identifier: MIT
// Copyright 2023 IROX Contributors
//

//!
//! Hexdump & Hex manipulation

use crate::bits::{Error, MutBits};
use alloc::vec::Vec;

/// 0-9, A-F
pub static HEX_UPPER_CHARS: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
];
/// 0-9, a-f
pub static HEX_LOWER_CHARS: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];

///
/// Dumps the contents of this data structure in a pretty 16 slot wide format, like the output of
/// `hexdump -C`
pub trait HexDump {
    /// Hexdump this data structure to stdout
    #[cfg(feature = "std")]
    fn hexdump(&self);

    /// Hexdump to the specified writer.
    fn hexdump_to<T: MutBits + ?Sized>(&self, out: &mut T) -> Result<(), Error>;
}

impl<S: AsRef<[u8]>> HexDump for S {
    #[cfg(feature = "std")]
    fn hexdump(&self) {
        let _ = self.hexdump_to(&mut crate::bits::BitsWrapper(&mut std::io::stdout().lock()));
    }

    fn hexdump_to<T: MutBits + ?Sized>(&self, out: &mut T) -> Result<(), Error> {
        let mut idx = 0;
        let val = self.as_ref();
        loop {
            write!(out, "{idx:08X}  ")?;
            let mut buf = Vec::new();
            for sidx in 0..16 {
                let Some(v) = val.get(idx + sidx) else {
                    break;
                };
                buf.push(*v);
            }
            for v in &buf {
                write!(out, "{v:02X} ")?;
            }
            for _i in 0..(16 - buf.len()) {
                write!(out, "   ")?;
            }
            write!(out, " |")?;
            for v in &buf {
                match *v {
                    0..=0x1F | 0x7F..=0xA0 | 0xFF => {
                        // nonprintables
                        write!(out, ".")?;
                    }
                    p => {
                        // printables
                        write!(out, "{}", p as char)?;
                    }
                }
            }
            for _i in 0..(16 - buf.len()) {
                write!(out, " ")?;
            }
            writeln!(out, "|")?;
            idx += 16;
            if buf.len() != 16 {
                break;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
#[cfg(feature = "std")]
mod tests {
    use crate::hex::HexDump;
    use alloc::vec::Vec;

    #[test]
    pub fn test() -> Result<(), crate::bits::Error> {
        let mut buf: Vec<u8> = Vec::new();
        for v in u8::MIN..=u8::MAX {
            buf.push(v);
        }

        buf.hexdump();

        Ok(())
    }
}