From c92e07853136c8371b6034d93a9d0f1be9e665c5 Mon Sep 17 00:00:00 2001 From: ddidderr Date: Sun, 7 Aug 2022 00:01:11 +0200 Subject: [PATCH] fix: add padding to the last line if it has less than 16 bytes --- src/lib.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 4682748..12bf2cb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +#[inline(always)] fn print_printable_or_dot(chunk: &[u8]) { for (idx, byte) in chunk.iter().enumerate() { if idx > 0 && idx % 8 == 0 { @@ -12,10 +13,12 @@ fn print_printable_or_dot(chunk: &[u8]) { } } +#[inline(always)] fn print_offset(offset: usize) { print!("{:08x} ", offset); } +#[inline(always)] fn print_data_hex(chunk: &[u8]) { for (idx, byte) in chunk.iter().enumerate() { if idx > 0 && idx % 8 == 0 { @@ -25,6 +28,25 @@ fn print_data_hex(chunk: &[u8]) { } } +#[inline(always)] +fn print_padding(chunk_len: usize) { + // only needs padding if we have less than 16 bytes to show + if chunk_len >= 16 { + return; + } + + // padding is 3 spaces per missing byte + for _ in 0..(16 - chunk_len) { + print!(" "); + } + + // if 8 or more bytes are missing we also need pad the space between + // 8-bytes left and 8-bytes right + if chunk_len <= 8 { + print!(" "); + } +} + pub fn print_hex(data: &[u8]) { let mut offset = 0usize; @@ -33,6 +55,7 @@ pub fn print_hex(data: &[u8]) { for chunk in chunks { print_offset(offset); print_data_hex(chunk); + print_padding(chunk.len()); print_printable_or_dot(chunk); println!(); offset += 16;