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
//! Regex cache

use std::{ops::Deref, str::FromStr, sync::Arc};

pub use anyhow::Error;
use anyhow::{Context, Result};
use dashmap::DashMap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};

/// A regex which can be used as a configuration.
///
/// While deserializing, this will be converted to a string and cached based on
/// the pattern.
#[derive(Debug, Clone)]
pub struct CachedRegex {
    regex: Arc<Regex>,
}

impl Deref for CachedRegex {
    type Target = Regex;

    fn deref(&self) -> &Self::Target {
        &self.regex
    }
}

impl CachedRegex {
    /// Get or create a cached regex. This will return the previous instance if
    /// it's already cached.
    pub fn new(input: &str) -> Result<Self> {
        static CACHE: Lazy<DashMap<String, Arc<Regex>, ahash::RandomState>> =
            Lazy::new(Default::default);

        if let Some(cache) = CACHE.get(input).as_deref().cloned() {
            return Ok(Self { regex: cache });
        }

        let regex =
            Regex::new(input).with_context(|| format!("failed to parse `{}` as regex", input))?;
        let regex = Arc::new(regex);

        CACHE.insert(input.to_owned(), regex.clone());

        Ok(CachedRegex { regex })
    }
}

impl<'de> Deserialize<'de> for CachedRegex {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error;

        let s = String::deserialize(deserializer)?;

        Self::new(&s).map_err(|err| D::Error::custom(err.to_string()))
    }
}

impl Serialize for CachedRegex {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let s = self.regex.as_str();

        serializer.serialize_str(s)
    }
}

/// This will panic for wrong patterns.
impl From<&'_ str> for CachedRegex {
    fn from(s: &'_ str) -> Self {
        Self::new(s).unwrap()
    }
}

impl FromStr for CachedRegex {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s)
    }
}