streamson_lib/matcher/regex.rs
1use regex::{self, Error as RegexError};
2use std::str::FromStr;
3
4use crate::{error, matcher::Matcher, path::Path, streamer::ParsedKind};
5
6/// Regex path matcher
7///
8/// It uses regex to match path
9///
10/// # Examples
11/// ```
12/// use streamson_lib::{handler, strategy::{self, Strategy}, matcher};
13///
14/// use std::{io, str::FromStr, sync::{Arc, Mutex}};
15///
16/// let handler = Arc::new(Mutex::new(handler::Output::new(io::stdout())));
17/// let matcher = matcher::Regex::from_str(r#"\{"[Uu]ser"\}\[\]"#).unwrap();
18///
19/// let mut trigger = strategy::Trigger::new();
20///
21/// trigger.add_matcher(
22/// Box::new(matcher),
23/// handler,
24/// );
25///
26/// for input in vec![
27/// br#"{"Users": [1,2]"#.to_vec(),
28/// br#", "users": [3, 4]}"#.to_vec(),
29/// ] {
30/// trigger.process(&input).unwrap();
31/// }
32///
33/// ```
34///
35#[derive(Debug, Clone)]
36pub struct Regex {
37 regex: regex::Regex,
38}
39
40impl Regex {
41 /// Creates new regex matcher
42 ///
43 /// # Arguments
44 /// * `rgx` - regex structure
45 pub fn new(rgx: regex::Regex) -> Self {
46 Self { regex: rgx }
47 }
48}
49
50impl Matcher for Regex {
51 fn match_path(&self, path: &Path, _kind: ParsedKind) -> bool {
52 let str_path: String = path.to_string();
53 self.regex.is_match(&str_path)
54 }
55}
56
57impl FromStr for Regex {
58 type Err = error::Matcher;
59 fn from_str(path: &str) -> Result<Self, Self::Err> {
60 let regex = regex::Regex::from_str(path)
61 .map_err(|e: RegexError| Self::Err::Parse(e.to_string()))?;
62 Ok(Self::new(regex))
63 }
64}