From 415a9c6ee1d20a4eb0158b6d40bedffb0ea924f9 Mon Sep 17 00:00:00 2001 From: Joey Hines Date: Mon, 11 Apr 2022 21:18:56 -0600 Subject: [PATCH] Fixed issue with array parse in CLI + octals were not ignoring base 10 zeros + binary parsing was trying to parse base 1 + clippy + fmt --- src/parser/mod.rs | 82 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 77 insertions(+), 5 deletions(-) diff --git a/src/parser/mod.rs b/src/parser/mod.rs index e9d522e..626fae4 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -30,13 +30,13 @@ fn bytes_from_str_array(src: Vec) -> Result, ByteArrayParseErr> if element.starts_with("0x") || element.starts_with("0X") { u8::from_str_radix(&element[2..], 16) } else if element.starts_with("0b") || element.starts_with("0B") { - u8::from_str_radix(&element[2..], 1) - } else if element.starts_with('h') || element.starts_with('h') { + u8::from_str_radix(&element[2..], 2) + } else if element.starts_with('h') || element.starts_with('H') { u8::from_str_radix(&element[1..], 16) - } else if let Some(value) = element.strip_prefix('0') { - u8::from_str_radix(value, 8) + } else if element.len() > 1 && element.starts_with('0') { + u8::from_str_radix(&element[1..], 8) } else { - str::parse(element) + element.parse() } }) .map(|e| e.map_err(ByteArrayParseErr::from)) @@ -62,3 +62,75 @@ pub fn parse_bytes_from_input_arg(src: Vec) -> Result, ByteArray bytes_from_str_array(str_arr) } + +#[cfg(test)] +mod tests { + use crate::parser::parse_bytes_from_input_arg; + + #[test] + fn parse_base_10_array() { + let array = vec!["[0, 1, 2, 3, 4]".to_string()]; + + let out = parse_bytes_from_input_arg(array).unwrap(); + + assert_eq!(out, vec![0, 1, 2, 3, 4]) + } + + #[test] + fn parse_base_2_array() { + let array = vec!["[0b0, 0b1, 0b10, 0b11, 0b100]".to_string()]; + + let out = parse_bytes_from_input_arg(array).unwrap(); + + assert_eq!(out, vec![0, 1, 2, 3, 4]) + } + + #[test] + fn parse_base_8_array() { + let array = vec!["[00, 01, 02, 03, 04]".to_string()]; + + let out = parse_bytes_from_input_arg(array).unwrap(); + + assert_eq!(out, vec![0, 1, 2, 3, 4]) + } + + #[test] + fn parse_base_16_array() { + let array = vec!["[0x0, 0x1, 0x2, h3, H4]".to_string()]; + + let out = parse_bytes_from_input_arg(array).unwrap(); + + assert_eq!(out, vec![0, 1, 2, 3, 4]) + } + + #[test] + fn parse_base_mixed() { + let array = vec!["[00 0x1, 2, h3, H4]".to_string()]; + + let out = parse_bytes_from_input_arg(array).unwrap(); + + assert_eq!(out, vec![0, 1, 2, 3, 4]) + } + + #[test] + fn parse_no_braces_multi_args() { + let array = vec![ + "0".to_string(), + "1".to_string(), + "2".to_string(), + "3".to_string(), + "4".to_string(), + ]; + let out = parse_bytes_from_input_arg(array).unwrap(); + + assert_eq!(out, vec![0, 1, 2, 3, 4]) + } + + #[test] + fn parse_no_braces_one_arg() { + let array = vec!["0 1 2 3 4".to_string()]; + let out = parse_bytes_from_input_arg(array).unwrap(); + + assert_eq!(out, vec![0, 1, 2, 3, 4]) + } +}