64 lines
1.8 KiB
Rust
64 lines
1.8 KiB
Rust
use std::io;
|
|
|
|
use crate::isatty;
|
|
|
|
use super::colormap::{map_char_to_color, map_u8_to_color};
|
|
|
|
const GLOBAL_BUFFER_LENGTH: usize = 16;
|
|
|
|
fn dump_to_hex(bytes: &mut [u8]) -> String {
|
|
let out_vec: Vec<String> = bytes
|
|
.chunks(2)
|
|
.map(|c| {
|
|
if c.len() == 2 {
|
|
format!("{}{}", map_u8_to_color(c[0]), map_u8_to_color(c[1]))
|
|
} else {
|
|
format!("{} ", map_u8_to_color(c[0]))
|
|
}
|
|
})
|
|
.collect();
|
|
let padding_length = (8 - out_vec.len()) * 5;
|
|
format!("{}{}", out_vec.join(" "), " ".repeat(padding_length))
|
|
}
|
|
|
|
fn dump_to_chr(bytes: &mut [u8]) -> String {
|
|
let out_vec: Vec<String> = bytes.iter().map(|ord| map_char_to_color(*ord)).collect();
|
|
out_vec.join("")
|
|
}
|
|
|
|
pub fn hexdump(mut reader: Box<dyn io::Read>, length: usize) {
|
|
let mut buf = [0; GLOBAL_BUFFER_LENGTH];
|
|
let mut offset: usize = 0;
|
|
let mut bytes_left = length;
|
|
|
|
loop {
|
|
let bytes_read = reader.read(&mut buf);
|
|
match bytes_read {
|
|
Ok(num) => {
|
|
let mut to_read = num;
|
|
if num > bytes_left {
|
|
to_read = bytes_left;
|
|
}
|
|
bytes_left -= to_read;
|
|
|
|
if to_read == 0 {
|
|
break;
|
|
} else {
|
|
println!(
|
|
"{:08x}: {:40}{}{:10}",
|
|
offset,
|
|
dump_to_hex(&mut buf[0..to_read]),
|
|
if isatty() { " ".to_string() } else { " ".to_string() },
|
|
dump_to_chr(&mut buf[0..to_read])
|
|
);
|
|
offset += GLOBAL_BUFFER_LENGTH;
|
|
}
|
|
}
|
|
Err(e) => {
|
|
eprintln!("hd: {}", e);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|