use regex::Regex;
use serde::{de::Error, Deserialize, Deserializer, Serialize};
use std::{
hash::{Hash, Hasher},
ops::Deref,
str::FromStr,
};
#[derive(Serialize, Debug, Clone)]
#[serde(transparent)]
pub struct HashedRegex {
pub string: String,
#[serde(skip_serializing)]
pub re: Regex,
}
impl HashedRegex {
pub fn new(s: &str) -> Result<Self, regex::Error> {
let string = s.to_string();
let re = Regex::new(s)?;
Ok(HashedRegex { string, re })
}
}
impl<'de> Deserialize<'de> for HashedRegex {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let string = String::deserialize(deserializer)?;
let re = Regex::new(&string).map_err(D::Error::custom)?;
Ok(HashedRegex { string, re })
}
}
impl Hash for HashedRegex {
fn hash<H: Hasher>(&self, state: &mut H) { self.string.hash(state); }
}
impl PartialEq for HashedRegex {
fn eq(&self, other: &Self) -> bool { self.string == other.string }
}
impl Eq for HashedRegex {}
impl FromStr for HashedRegex {
type Err = regex::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> { HashedRegex::new(s) }
}
impl Deref for HashedRegex {
type Target = regex::Regex;
fn deref(&self) -> ®ex::Regex { &self.re }
}