1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
    Appellation: extractor <module>
    Creator: FL03 <jo3mccain@icloud.com>
    Description:
        ... Summary ...
*/
/// Implements an extraction tool designed to iterate through a given string, collecting
/// valid data points into a vector
#[derive(Clone, Debug, Hash, PartialEq)]
pub struct Extractor<'a> {
    pub breakpoint: char,
    pub data: String,
    pub exclude: &'a [char],
}

impl Extractor<'_> {
    fn constructor(breakpoint: char, data: String, exclude: &'static [char]) -> Self {
        Self {
            breakpoint,
            data,
            exclude,
        }
    }
    pub fn exclude_chars() -> &'static [char] {
        let to_skip = &[' ', ',', '[', ']', '.'];
        to_skip
    }
    pub fn extract<T>(&self) -> Vec<T>
    where
        T: Clone + std::str::FromStr,
        <T as std::str::FromStr>::Err: std::fmt::Debug,
    {
        let trimmed: &str = &self.data.trim_matches(self.exclude);
        trimmed
            .split(self.breakpoint)
            .map(|i| i.trim_matches(self.exclude).parse::<T>().unwrap())
            .collect()
    }
    pub fn new(breakpoint: char, data: String) -> Self {
        Self::constructor(breakpoint, data, Self::exclude_chars())
    }
}

#[cfg(test)]
mod tests {
    use super::Extractor;

    #[test]
    fn test_extractor() {
        let a = Extractor::new('.', "0.0.0.0".to_string());
        let b = Extractor::new(',', "[0, 0, 0, 0]".to_string());

        let a_data = a.extract::<u8>();
        let b_data = b.extract::<u8>();
        let expected: Vec<u8> = vec![0, 0, 0, 0];

        assert_eq!(a_data, expected.clone());
        assert_eq!(b_data, expected)
    }
}