flams_utils/
regex.rs

1#[cfg(target_family = "wasm")]
2use js_regexp::RegExp as JRegex;
3#[cfg(not(target_family = "wasm"))]
4use regex::Regex as IRegex;
5
6#[cfg(not(target_family = "wasm"))]
7#[derive(Debug, Clone)]
8pub struct Regex(IRegex);
9#[cfg(target_family = "wasm")]
10#[derive(Debug, Clone)]
11#[cfg_attr(feature = "wasm", derive(tsify_next::Tsify))]
12#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
13pub struct Regex(String);
14
15impl std::fmt::Display for Regex {
16    #[inline]
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        f.write_str(self.as_str())
19    }
20}
21
22impl Regex {
23    pub fn is_match(&self, text: &str) -> bool {
24        #[cfg(not(target_family = "wasm"))]
25        {
26            self.0.is_match(text)
27        }
28        #[cfg(target_family = "wasm")]
29        {
30            crate::unwrap!(JRegex::new(&self.0, js_regexp::flags!("")).ok())
31                .exec(text)
32                .is_some()
33        }
34    }
35    pub fn as_str(&self) -> &str {
36        #[cfg(not(target_family = "wasm"))]
37        {
38            self.0.as_str()
39        }
40        #[cfg(target_family = "wasm")]
41        {
42            &self.0
43        }
44    }
45    pub fn new(s: &str) -> Result<Self, String> {
46        #[cfg(not(target_family = "wasm"))]
47        {
48            IRegex::new(s).map(Self).map_err(|e| format!("{}", e))
49        }
50        #[cfg(target_family = "wasm")]
51        {
52            JRegex::new(s, js_regexp::flags!(""))
53                .map(|_| Self(s.to_string()))
54                .map_err(|_| "Invalid Regular Expression".to_string())
55        }
56        // https://docs.rs/js-regexp/0.2.1/js_regexp/struct.FlagSets.html
57    }
58}
59
60#[cfg(feature = "serde")]
61mod regex_serde {
62    use super::Regex;
63    impl serde::Serialize for Regex {
64        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
65        where
66            S: serde::Serializer,
67        {
68            serializer.serialize_str(self.as_str())
69        }
70    }
71
72    impl<'de> serde::Deserialize<'de> for Regex {
73        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
74        where
75            D: serde::Deserializer<'de>,
76        {
77            let s = String::deserialize(deserializer)?;
78            Regex::new(&s).map_err(serde::de::Error::custom)
79        }
80    }
81}