53 lines
1.5 KiB
Rust
53 lines
1.5 KiB
Rust
|
use std::num::ParseIntError;
|
||
|
|
||
|
#[derive(Debug, Clone)]
|
||
|
pub enum ByteArrayParseErr {
|
||
|
EmptySrcArray,
|
||
|
ParseIntError(ParseIntError),
|
||
|
}
|
||
|
|
||
|
impl From<ParseIntError> for ByteArrayParseErr {
|
||
|
fn from(e: ParseIntError) -> Self {
|
||
|
ByteArrayParseErr::ParseIntError(e)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn bytes_from_str_array(src: Vec<String>) -> Result<Vec<u8>, ByteArrayParseErr> {
|
||
|
src.iter()
|
||
|
.map(|element| {
|
||
|
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[1..], 16)
|
||
|
} else if let Some(value) = element.strip_prefix('0') {
|
||
|
u8::from_str_radix(value, 8)
|
||
|
} else {
|
||
|
str::parse(element)
|
||
|
}
|
||
|
})
|
||
|
.map(|e| e.map_err( ByteArrayParseErr::from ))
|
||
|
.collect()
|
||
|
}
|
||
|
|
||
|
pub fn parse_bytes_from_input_arg(src: Vec<String>) -> Result<Vec<u8>, ByteArrayParseErr> {
|
||
|
if src.is_empty() {
|
||
|
return Err(ByteArrayParseErr::EmptySrcArray);
|
||
|
}
|
||
|
|
||
|
let str_arr = if src.len() == 1 {
|
||
|
src[0]
|
||
|
.replace(",", " ")
|
||
|
.replace("[", "")
|
||
|
.replace("]", "")
|
||
|
.split_whitespace()
|
||
|
.map(|s| s.to_string())
|
||
|
.collect()
|
||
|
} else {
|
||
|
src
|
||
|
};
|
||
|
|
||
|
bytes_from_str_array(str_arr)
|
||
|
}
|