]>
Commit | Line | Data |
---|---|---|
e89a52c3 DM |
1 | use 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). | |
9 | pub 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 | ||
16 | impl fmt::Debug for ConstRegexPattern { | |
17 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
18 | write!(f, "{:?}", self.regex_string) | |
19 | } | |
20 | } | |
fa83cbde | 21 | |
a6ce1e43 | 22 | /// Macro to generate a ConstRegexPattern |
e89a52c3 | 23 | /// |
446ee314 | 24 | /// ``` |
446ee314 DM |
25 | /// # use proxmox_api::*; |
26 | /// # | |
e89a52c3 DM |
27 | /// const_regex!{ |
28 | /// FILE_EXTENSION_REGEX = r".*\.([a-zA-Z]+)$"; | |
29 | /// pub SHA256_HEX_REGEX = r"^[a-f0-9]{64}$"; | |
30 | /// } | |
31 | /// ``` | |
a6ce1e43 WB |
32 | #[macro_export] |
33 | macro_rules! const_regex { | |
34 | () => {}; | |
35 | ($(#[$attr:meta])* pub ($($vis:tt)+) $name:ident = $regex:expr; $($rest:tt)*) => { | |
36 | $crate::const_regex! { (pub ($($vis)+)) $(#[$attr])* $name = $regex; $($rest)* } | |
37 | }; | |
38 | ($(#[$attr:meta])* pub $name:ident = $regex:expr; $($rest:tt)*) => { | |
39 | $crate::const_regex! { (pub) $(#[$attr])* $name = $regex; $($rest)* } | |
40 | }; | |
41 | ($(#[$attr:meta])* $name:ident = $regex:expr; $($rest:tt)*) => { | |
42 | $crate::const_regex! { () $(#[$attr])* $name = $regex; $($rest)* } | |
43 | }; | |
44 | ( | |
45 | ($($pub:tt)*) $(#[$attr:meta])* $name:ident = $regex:expr; | |
46 | $($rest:tt)* | |
47 | ) => { | |
446ee314 DM |
48 | $(#[$attr])* $($pub)* const $name: $crate::const_regex::ConstRegexPattern = |
49 | $crate::const_regex::ConstRegexPattern { | |
a6ce1e43 WB |
50 | regex_string: $regex, |
51 | regex_obj: (|| -> &'static ::regex::Regex { | |
52 | ::lazy_static::lazy_static! { | |
53 | static ref SCHEMA: ::regex::Regex = ::regex::Regex::new($regex).unwrap(); | |
54 | } | |
55 | &SCHEMA | |
56 | }) | |
57 | }; | |
58 | ||
59 | $crate::const_regex! { $($rest)* } | |
60 | }; | |
61 | } |