tramex_tools/interface/
functions.rs

1//! useful functions
2
3use crate::{
4    errors::{ErrorCode, TramexError},
5    tramex_error,
6};
7
8/// Extract hexadecimal data from a vector of strings.
9/// # Errors
10/// Returns a TramexError if the hexe representation could not be extracted.
11pub fn extract_hexe<T: AsRef<str>>(data: &[T]) -> Result<Vec<u8>, TramexError> {
12    let iter = data.iter().filter(|one_string| {
13        if let Some(first_char) = one_string.as_ref().trim().chars().next() {
14            return first_char.is_numeric();
15        }
16        false
17    });
18    let mut data: Vec<String> = Vec::new();
19    for one_string in iter {
20        let trimmed = one_string.as_ref().trim();
21        if trimmed.len() > 57 {
22            let str_piece = &trimmed[7..56];
23            let chars_only: String = str_piece.chars().filter(|c| !c.is_whitespace()).collect();
24            data.push(chars_only);
25        } else {
26            return Err(tramex_error!(
27                format!("Error decoding hexe {:?} ({})", trimmed, trimmed.len()),
28                ErrorCode::HexeDecodingError
29            ));
30        }
31    }
32    let mut hexe: Vec<u8> = Vec::new();
33    for one_string in data {
34        let mut i = 0;
35        while i < one_string.len() {
36            let hex = &one_string[i..i + 2];
37            if let Ok(hexa) = u8::from_str_radix(hex, 16) {
38                hexe.push(hexa);
39            }
40            i += 2;
41        }
42    }
43    Ok(hexe)
44}