postal_code/
regex.rs

1crate::ix!();
2
3#[macro_export]
4macro_rules! define_postal_code_regexes {
5    ($id:ident, { $($c:ident => $pattern:expr),+ $(,)? }) => {
6        paste::paste! {
7            // Define a unique module name based on the user-supplied $id
8            #[allow(non_snake_case)]
9            mod [<__internal_ $id >] {
10                use super::*;
11                use once_cell::sync::Lazy;
12                use ::regex::Regex; // Use ::regex to disambiguate
13                
14                $(
15                    #[allow(non_upper_case_globals)]
16                    pub static [<REGEX_ $c>]: Lazy<Result<Regex, PostalCodeConstructionError>> = Lazy::new(|| {
17                        Regex::new($pattern)
18                            .map_err(|_| PostalCodeConstructionError::RegexInitializationError { country: Country::$c })
19                    });
20                )+
21            }
22
23            $(
24                pub use [<__internal_ $id >]::[<REGEX_ $c>];
25            )+
26        }
27    }
28}
29
30define_postal_code_regexes!{
31    Set1, {
32        USA           => r"^\d{5}(-\d{4})?$",
33        Canada        => r"^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$",
34        UnitedKingdom => r"^(GIR 0AA)$|((([A-Z]{1,2}[0-9][A-Z0-9]?)|(([A-Z]{1,2}[0-9]{1,2})|(([A-Z]{1,2}[0-9][A-Z])|([A-Z]{1,2}[0-9]{2})))) [0-9][A-Z]{2})$",
35        France        => r"^\d{5}$",
36    }
37}
38
39// NOTE: these two `define_postal_code_regexes` invoations are only separated to show an example of
40// how a user can install more regexes using this macro
41//
42define_postal_code_regexes!{
43    Set2, {
44        Germany => r"^\d{5}$",
45        Italy   => r"^\d{5}$",
46    }
47}