Skip to main content

garde_fr/rules/
pattern.rs

1//! Pattern validation.
2//!
3//! The pattern argument can be a regular expression provided as a string literal, which is then parsed by the [`regex`] crate (if the `regex` feature is enabled).
4//!
5//! ```rust
6//! #[derive(garde::Validate)]
7//! struct Test {
8//!     #[garde(pattern(r"[a-zA-Z0-9][a-zA-Z0-9_]+"))]
9//!     v: String,
10//! }
11//! ```
12//!
13//! Alternatively, it can be an expression of type implementing [`Matcher`] or one that dereferences to a [`Matcher`].
14//! [`Matcher`] is implemented for `regex::Regex` (if the `regex` feature is enabled) and `once_cell::sync::Lazy<T>` with any `T: Matcher`.
15//! Please note that the expression will be evaluated each time `validate` is called, so avoid doing any expensive work in the expression.
16//! If the work is unavoidable, at least try to amortize it, such as by using `once_cell::Lazy` or the nightly-only `std::sync::LazyLock`.
17//!
18//! ```rust
19//! use once_cell::sync::Lazy;
20//! use regex::Regex;
21//!
22//! static LAZY_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[a-zA-Z0-9][a-zA-Z0-9_]+").unwrap());
23//!
24//! #[derive(garde::Validate)]
25//! struct Test {
26//!     #[garde(pattern(LAZY_RE))]
27//!     v: String,
28//! }
29//! ```
30//!
31//! The entrypoint is the [`Pattern`] trait. Implementing this trait for a type allows that type to be used with the `#[garde(pattern(...))]` rule.
32//!
33//! This trait has a blanket implementation for all `T: garde::rules::AsStr`.
34
35use super::AsStr;
36use crate::error::Error;
37
38pub fn apply<T: Pattern, M: Matcher>(v: &T, (pat,): (&M,)) -> Result<(), Error> {
39    if !v.validate_pattern(pat) {
40        return Err(Error::new(format!(
41            "ne correspond pas au pattern /{}/",
42            pat.as_str()
43        )));
44    }
45    Ok(())
46}
47
48pub trait Matcher: AsStr {
49    /// Returns true if and only if there is a match for the pattern anywhere in the haystack given.
50    fn is_match(&self, haystack: &str) -> bool;
51}
52
53pub trait Pattern {
54    fn validate_pattern<M: Matcher>(&self, matcher: &M) -> bool;
55}
56
57impl<T: AsStr> Pattern for T {
58    fn validate_pattern<M: Matcher>(&self, matcher: &M) -> bool {
59        matcher.is_match(self.as_str())
60    }
61}
62
63impl<T: Pattern> Pattern for Option<T> {
64    fn validate_pattern<M: Matcher>(&self, matcher: &M) -> bool {
65        match self {
66            Some(value) => value.validate_pattern(matcher),
67            None => true,
68        }
69    }
70}
71
72#[cfg(all(
73    feature = "regex",
74    feature = "js-sys",
75    target_arch = "wasm32",
76    target_os = "unknown"
77))]
78#[doc(hidden)]
79pub mod regex_js_sys {
80    pub use ::js_sys::RegExp;
81
82    use super::*;
83
84    impl Matcher for RegExp {
85        fn is_match(&self, haystack: &str) -> bool {
86            self.test(haystack)
87        }
88    }
89
90    impl AsStr for RegExp {
91        fn as_str(&self) -> &str {
92            "[Not supported in JS]"
93        }
94    }
95
96    pub struct SyncWrapper<T>(T);
97
98    impl<T> SyncWrapper<T> {
99        /// Safety: You have to ensure that this value is never shared or sent between threads unless the inner value supports it
100        pub const unsafe fn new(inner: T) -> Self {
101            Self(inner)
102        }
103    }
104
105    impl<T: AsStr> AsStr for SyncWrapper<T> {
106        fn as_str(&self) -> &str {
107            self.0.as_str()
108        }
109    }
110
111    impl<T: Matcher> Matcher for SyncWrapper<T> {
112        fn is_match(&self, haystack: &str) -> bool {
113            self.0.is_match(haystack)
114        }
115    }
116
117    unsafe impl<T> Send for SyncWrapper<T> {}
118    unsafe impl<T> Sync for SyncWrapper<T> {}
119
120    pub type StaticPattern = once_cell::sync::Lazy<SyncWrapper<RegExp>>;
121
122    #[macro_export]
123    macro_rules! __init_js_sys_pattern {
124        ($pat:literal) => {
125            $crate::rules::pattern::regex_js_sys::StaticPattern::new(|| {
126                // Safety: `wasm32-unknown-unknown` is inherently single-threaded. Therefore `Send` and `Sync` aren't really relevant
127                unsafe { $crate::rules::pattern::regex_js_sys::SyncWrapper::new(::js_sys::RegExp::new($pat, "u")) }
128            })
129        };
130    }
131    pub use crate::__init_js_sys_pattern as init_pattern;
132}
133
134#[cfg(feature = "regex")]
135#[doc(hidden)]
136pub mod regex {
137    pub use ::regex::Regex;
138
139    use super::*;
140
141    impl Matcher for Regex {
142        fn is_match(&self, haystack: &str) -> bool {
143            self.is_match(haystack)
144        }
145    }
146
147    impl<T: Matcher> Matcher for once_cell::sync::Lazy<T> {
148        fn is_match(&self, haystack: &str) -> bool {
149            once_cell::sync::Lazy::force(self).is_match(haystack)
150        }
151    }
152
153    impl AsStr for Regex {
154        fn as_str(&self) -> &str {
155            self.as_str()
156        }
157    }
158
159    impl<T: AsStr> AsStr for once_cell::sync::Lazy<T> {
160        fn as_str(&self) -> &str {
161            once_cell::sync::Lazy::force(self).as_str()
162        }
163    }
164
165    pub type StaticPattern = once_cell::sync::Lazy<Regex>;
166
167    #[macro_export]
168    macro_rules! __init_pattern {
169        ($pat:literal) => {
170            $crate::rules::pattern::regex::StaticPattern::new(|| {
171                $crate::rules::pattern::regex::Regex::new($pat).unwrap()
172            })
173        };
174    }
175    pub use crate::__init_pattern as init_pattern;
176}