commit 07517fbd6bed63ad794e7790d45b4f369b5f11ff Author: ddidderr Date: Tue Apr 5 08:18:12 2022 +0200 hexhex: a simple hex viewer library for testing purposes. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..96ef6c0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..bc5149b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "hexhex" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..4682748 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,40 @@ +fn print_printable_or_dot(chunk: &[u8]) { + for (idx, byte) in chunk.iter().enumerate() { + if idx > 0 && idx % 8 == 0 { + print!(" "); + } + + if *byte >= 32 && *byte <= 126 { + print!("{}", String::from_utf8(vec![*byte]).unwrap()); + } else { + print!("."); + } + } +} + +fn print_offset(offset: usize) { + print!("{:08x} ", offset); +} + +fn print_data_hex(chunk: &[u8]) { + for (idx, byte) in chunk.iter().enumerate() { + if idx > 0 && idx % 8 == 0 { + print!(" "); + } + print!("{:02x} ", byte); + } +} + +pub fn print_hex(data: &[u8]) { + let mut offset = 0usize; + + let chunks: Vec<&[u8]> = data.chunks(16).collect(); + + for chunk in chunks { + print_offset(offset); + print_data_hex(chunk); + print_printable_or_dot(chunk); + println!(); + offset += 16; + } +}