Switched rules to Regexes, added Regex wrapper for serde

This commit is contained in:
Lucien Cartier-Tilet 2020-03-29 03:10:19 +02:00
parent d13836e433
commit 6be0f7e8f6
Signed by: phundrak
GPG Key ID: BD7789E705CB8DCA
2 changed files with 88 additions and 1 deletions

View File

@ -9,6 +9,9 @@ use log::{error, info};
pub mod utils; pub mod utils;
use utils::SettingsType; use utils::SettingsType;
pub mod regex_wrapper;
use regex_wrapper::Regex;
/// Current version of the ruleset. It will help determine if the ruleset is /// Current version of the ruleset. It will help determine if the ruleset is
/// outdated or from a more recent version of the software than the one being in /// outdated or from a more recent version of the software than the one being in
/// use. /// use.
@ -121,7 +124,7 @@ pub struct Settings {
/// a regex to be matched while the second represents the change /// a regex to be matched while the second represents the change
/// to be made to the input data. /// to be made to the input data.
#[serde(default)] #[serde(default)]
rules: Vec<(String, String)>, pub rules: Vec<(Regex, Regex)>,
} }
/// Representation inside the crate of LangEvolves settings. /// Representation inside the crate of LangEvolves settings.

View File

@ -0,0 +1,84 @@
// extern crate serde;
// extern crate regex;
// use serde::{Deserialize, Serialize};
// #[derive(Clone, Debug, Deserialize, Serialize)]
// #[serde(transparent)]
// pub struct Regex(regex::Regex);
// #[derive(Clone, Debug, Deserialize, Serialize)]
// #[serde(remote = "regex::Regex")]
// pub struct RegexDef{
// #[serde(getter = "regex::Regex::to_string")]
// r: String
// }
use std::{fmt, ops};
#[derive(Clone, Debug)]
pub struct Regex(regex::Regex);
impl Regex {
pub fn new(s: &str) -> Self {
Self(regex::Regex::new(s).unwrap())
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
pub fn to_string(&self) -> String {
self.0.to_string()
}
}
impl ops::Deref for Regex {
type Target = regex::Regex;
fn deref(&self) -> &regex::Regex {
&self.0
}
}
impl<'de> serde::Deserialize<'de> for Regex {
fn deserialize<D>(de: D) -> Result<Regex, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{Error, Visitor};
struct RegexVisitor;
impl<'de> Visitor<'de> for RegexVisitor {
type Value = Regex;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a regular expression pattern")
}
fn visit_str<E: Error>(self, v: &str) -> Result<Regex, E> {
regex::Regex::new(v)
.map(Regex)
.map_err(|err| E::custom(err.to_string()))
}
}
de.deserialize_str(RegexVisitor)
}
}
use serde::{Serialize, Serializer};
impl Serialize for Regex {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.0.as_str())
}
}
impl PartialEq for Regex {
fn eq(&self, other: &Self) -> bool {
self.0.to_string() == other.0.to_string()
}
}
impl Eq for Regex {}