use crate::errors::{HexDumpProblem, InvalidHexDump};
use std::str::FromStr;
pub const HEX_OFFSET_WIDTH: usize = 8;
const HEX_OFFSET_SEPARATOR: &str = " ";
pub const HEX_BYTES_PER_LINE: usize = 16;
pub fn hex_lines(bytes: &[u8], per_line: usize) -> Vec<String> {
bytes
.chunks(per_line)
.enumerate()
.map(|(line, chunk)| {
let hex: Vec<String> = chunk.iter().map(|byte| format!("{byte:02x}")).collect();
format!(
"{:0width$x}{HEX_OFFSET_SEPARATOR}{}",
line * per_line,
hex.join(" "),
width = HEX_OFFSET_WIDTH
)
})
.collect()
}
pub struct HexDump(Vec<u8>);
impl HexDump {
pub fn into_value(self) -> Vec<u8> {
self.0
}
}
impl FromStr for HexDump {
type Err = InvalidHexDump;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let mut bytes = Vec::new();
for (index, line) in text.lines().enumerate() {
let mut digits = Vec::new();
for character in without_offset(line).chars() {
if character.is_whitespace() {
continue;
}
let Some(digit) = character.to_digit(16) else {
return Err(InvalidHexDump {
line: index + 1,
problem: HexDumpProblem::NotHexDigit(character),
});
};
digits.push(u8::try_from(digit).expect("a hexadecimal digit is below 16"));
}
if digits.len() % 2 != 0 {
return Err(InvalidHexDump {
line: index + 1,
problem: HexDumpProblem::OddDigits,
});
}
bytes.extend(digits.chunks(2).map(|pair| pair[0] << 4 | pair[1]));
}
Ok(Self(bytes))
}
}
fn without_offset(line: &str) -> &str {
let line = line.trim_start();
match line.split_at_checked(HEX_OFFSET_WIDTH) {
Some((offset, bytes))
if offset.chars().all(|digit| digit.is_ascii_hexdigit())
&& bytes.starts_with(HEX_OFFSET_SEPARATOR) =>
{
bytes
}
_ => line,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_hex_dump_reads_back_without_its_offsets_and_whitespace_and_an_error_names_its_line() {
let edited = "00000000 01 02 03\n0405 06\n\n00000010 ff\n";
let read = edited.parse::<HexDump>().map(HexDump::into_value);
let odd = "00000000 01 02\n00000002 0\n".parse::<HexDump>();
let not_hex = "01 0x".parse::<HexDump>();
assert_eq!(read.ok(), Some(vec![1, 2, 3, 4, 5, 6, 255]));
assert!(matches!(
odd,
Err(InvalidHexDump {
line: 2,
problem: HexDumpProblem::OddDigits
})
));
assert!(matches!(
not_hex,
Err(InvalidHexDump {
line: 1,
problem: HexDumpProblem::NotHexDigit('x')
})
));
}
#[test]
fn eight_digits_not_followed_by_the_two_spaces_of_an_offset_are_bytes() {
let packed = "deadbeef\n".parse::<HexDump>().map(HexDump::into_value);
let grouped = "01020304 05\n".parse::<HexDump>().map(HexDump::into_value);
assert_eq!(packed.ok(), Some(vec![0xde, 0xad, 0xbe, 0xef]));
assert_eq!(grouped.ok(), Some(vec![1, 2, 3, 4, 5]));
}
}