1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use std::borrow::Cow;
use std::cell::OnceCell;
use std::sync::{Arc, Mutex, OnceLock};

use regex::Regex;

pub trait AsRegex {
    fn as_regex(&self) -> Cow<Regex>;
}

impl AsRegex for Regex {
    fn as_regex(&self) -> Cow<Regex> {
        Cow::Borrowed(self)
    }
}

impl<T> AsRegex for &T
    where T: AsRegex {
    fn as_regex(&self) -> Cow<Regex> {
        T::as_regex(self)
    }
}

impl AsRegex for &OnceLock<Regex> {
    fn as_regex(&self) -> Cow<Regex> {
        Cow::Borrowed(self.get().unwrap())
    }
}

impl AsRegex for &Mutex<OnceCell<Regex>> {
    fn as_regex(&self) -> Cow<Regex> {
        Cow::Owned(self.lock().unwrap().get().unwrap().clone())
    }
}

impl AsRegex for &Mutex<OnceLock<Regex>> {
    fn as_regex(&self) -> Cow<Regex> {
        Cow::Owned(self.lock().unwrap().get().unwrap().clone())
    }
}

impl AsRegex for &Arc<Mutex<OnceCell<Regex>>> {
    fn as_regex(&self) -> Cow<Regex> {
        Cow::Owned(self.lock().unwrap().get().unwrap().clone())
    }
}

impl AsRegex for &Arc<Mutex<OnceLock<Regex>>> {
    fn as_regex(&self) -> Cow<Regex> {
        Cow::Owned(self.lock().unwrap().get().unwrap().clone())
    }
}

pub trait ValidateRegex {
    fn validate_regex(&self, regex: impl AsRegex) -> bool;
}

impl<T> ValidateRegex for &T
    where T: ValidateRegex {
    fn validate_regex(&self, regex: impl AsRegex) -> bool {
        T::validate_regex(self, regex)
    }
}

impl<T> ValidateRegex for Option<T>
    where T: ValidateRegex {
    fn validate_regex(&self, regex: impl AsRegex) -> bool {
        if let Some(h) = self {
            T::validate_regex(h, regex)
        } else {
            true
        }
    }
}

impl<'cow, T> ValidateRegex for Cow<'cow, T>
    where T: ToOwned + ?Sized,
          for<'a> &'a T: ValidateRegex
{
    fn validate_regex(&self, regex: impl AsRegex) -> bool {
        self.as_ref().validate_regex(regex)
    }
}

impl ValidateRegex for String {
    fn validate_regex(&self, regex: impl AsRegex) -> bool {
        regex.as_regex().is_match(self)
    }
}

impl ValidateRegex for &str {
    fn validate_regex(&self, regex: impl AsRegex) -> bool {
        regex.as_regex().is_match(self)
    }
}