]> git.proxmox.com Git - proxmox.git/blame - proxmox-schema/src/const_regex.rs
clippy fix: needless borrow
[proxmox.git] / proxmox-schema / src / const_regex.rs
CommitLineData
e89a52c3
DM
1use std::fmt;
2
3/// Helper to represent const regular expressions
4///
5/// The current Regex::new() function is not `const_fn`. Unless that
6/// works, we use `ConstRegexPattern` to represent static regular
7/// expressions. Please use the `const_regex` macro to generate
8/// instances of this type (uses lazy_static).
9pub struct ConstRegexPattern {
10 /// This is only used for documentation and debugging
11 pub regex_string: &'static str,
12 /// This function return the the actual Regex
13 pub regex_obj: fn() -> &'static regex::Regex,
14}
15
16impl fmt::Debug for ConstRegexPattern {
17 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18 write!(f, "{:?}", self.regex_string)
19 }
20}
fa83cbde 21
8a6e741d
WB
22impl std::ops::Deref for ConstRegexPattern {
23 type Target = regex::Regex;
24
25 fn deref(&self) -> &Self::Target {
26 (self.regex_obj)()
27 }
28}
29
a6ce1e43 30/// Macro to generate a ConstRegexPattern
e89a52c3 31///
446ee314 32/// ```
41f3fdfe
WB
33/// use proxmox_schema::const_regex;
34///
e89a52c3
DM
35/// const_regex!{
36/// FILE_EXTENSION_REGEX = r".*\.([a-zA-Z]+)$";
37/// pub SHA256_HEX_REGEX = r"^[a-f0-9]{64}$";
38/// }
39/// ```
a6ce1e43
WB
40#[macro_export]
41macro_rules! const_regex {
e3a78d63
WB
42 ($(
43 $(#[$attr:meta])*
44 $vis:vis $name:ident = $regex:expr;
45 )+) => { $(
41f3fdfe
WB
46 $(#[$attr])* $vis const $name: $crate::ConstRegexPattern =
47 $crate::ConstRegexPattern {
a6ce1e43
WB
48 regex_string: $regex,
49 regex_obj: (|| -> &'static ::regex::Regex {
41f3fdfe 50 $crate::semver_exempt::lazy_static! {
a6ce1e43
WB
51 static ref SCHEMA: ::regex::Regex = ::regex::Regex::new($regex).unwrap();
52 }
53 &SCHEMA
54 })
55 };
e3a78d63 56 )+ };
a6ce1e43 57}
b0ef4051
WB
58
59#[cfg(feature = "test-harness")]
60impl Eq for ConstRegexPattern {}
61
62#[cfg(feature = "test-harness")]
63impl PartialEq for ConstRegexPattern {
64 fn eq(&self, rhs: &Self) -> bool {
65 self.regex_string == rhs.regex_string
66 }
67}