use crate::error::Error;
use array_bytes::{hex2bytes, hex_bytes2hex_str};
use clap::Args;
use std::io::BufRead;
#[derive(Debug, Clone, Args)]
pub struct MessageParams {
#[arg(long)]
message: Option<String>,
#[arg(long)]
hex: bool,
}
impl MessageParams {
pub(crate) fn message_from<F, R>(&self, create_reader: F) -> Result<Vec<u8>, Error>
where
R: BufRead,
F: FnOnce() -> R,
{
let raw = match &self.message {
Some(raw) => raw.as_bytes().to_vec(),
None => {
let mut raw = vec![];
create_reader().read_to_end(&mut raw)?;
raw
},
};
if self.hex {
hex2bytes(hex_bytes2hex_str(&raw)?).map_err(Into::into)
} else {
Ok(raw)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn message_decode_immediate() {
for (name, input, hex, output) in test_closures() {
println!("Testing: immediate_{}", name);
let params = MessageParams { message: Some(input.into()), hex };
let message = params.message_from(|| std::io::stdin().lock());
match output {
Some(output) => {
let message = message.expect(&format!("{}: should decode but did not", name));
assert_eq!(message, output, "{}: decoded a wrong message", name);
},
None => {
message.err().expect(&format!("{}: should not decode but did", name));
},
}
}
}
#[test]
fn message_decode_stream() {
for (name, input, hex, output) in test_closures() {
println!("Testing: stream_{}", name);
let params = MessageParams { message: None, hex };
let message = params.message_from(|| input.as_bytes());
match output {
Some(output) => {
let message = message.expect(&format!("{}: should decode but did not", name));
assert_eq!(message, output, "{}: decoded a wrong message", name);
},
None => {
message.err().expect(&format!("{}: should not decode but did", name));
},
}
}
}
fn test_closures() -> Vec<(&'static str, &'static str, bool, Option<&'static [u8]>)> {
vec![
("decode_no_hex_works", "Hello this is not hex", false, Some(b"Hello this is not hex")),
("decode_no_hex_with_hex_string_works", "0xffffffff", false, Some(b"0xffffffff")),
("decode_hex_works", "0x00112233", true, Some(&[0, 17, 34, 51])),
("decode_hex_without_prefix_works", "00112233", true, Some(&[0, 17, 34, 51])),
("decode_hex_uppercase_works", "0xaAbbCCDd", true, Some(&[170, 187, 204, 221])),
("decode_hex_wrong_len_errors", "0x0011223", true, None),
]
}
}