FromStr for BytesPattern

This commit is contained in:
Dmitry Belyaev 2022-08-27 22:53:46 +03:00
parent 3deb961413
commit 22bdffa92f
Signed by: b4tman
GPG Key ID: 41A00BF15EA7E5F3
2 changed files with 10 additions and 4 deletions

View File

@ -19,7 +19,7 @@ fn main() {
let replacement = let replacement =
binnvecs!("06 5A 18 74 2D 62 12 6A 13 4A 2B 0E 6F 0F 36 7A 28 0A 37 67 0A 4B 01 73 14"); binnvecs!("06 5A 18 74 2D 62 12 6A 13 4A 2B 0E 6F 0F 36 7A 28 0A 37 67 0A 4B 01 73 14");
let pattern = BytesPattern::from(src_pattern); let pattern = src_pattern.parse().unwrap();
let file = File::open(src_file).expect("src open"); let file = File::open(src_file).expect("src open");

View File

@ -2,6 +2,7 @@ extern crate data_encoding;
use data_encoding::HEXUPPER; use data_encoding::HEXUPPER;
use std::ops::Deref; use std::ops::Deref;
use std::str::FromStr;
pub struct BytesPattern { pub struct BytesPattern {
bytes: Vec<u8>, bytes: Vec<u8>,
@ -46,8 +47,13 @@ impl BytesPattern {
} }
} }
impl From<&str> for BytesPattern { impl FromStr for BytesPattern {
fn from(str_val: &str) -> Self { type Err = &'static str;
fn from_str(str_val: &str) -> Result<Self, Self::Err> {
if str_val.is_empty() {
return Err("string is empty");
}
let mut elements: Vec<&str> = str_val.split(' ').collect(); let mut elements: Vec<&str> = str_val.split(' ').collect();
let mask: Vec<bool> = elements.iter().map(|item| *item == "??").collect(); let mask: Vec<bool> = elements.iter().map(|item| *item == "??").collect();
@ -61,7 +67,7 @@ impl From<&str> for BytesPattern {
.decode(elements.join("").as_bytes()) .decode(elements.join("").as_bytes())
.expect("decode pattern"); .expect("decode pattern");
Self::from((bytes, mask)) Ok(Self::from((bytes, mask)))
} }
} }