Optimized rule rewriting

This commit is contained in:
Lucien Cartier-Tilet 2020-04-04 18:54:46 +02:00
parent 23e3acb182
commit dbbb1616dd
Signed by: phundrak
GPG Key ID: BD7789E705CB8DCA
1 changed files with 26 additions and 21 deletions

View File

@ -284,32 +284,36 @@ impl Settings {
RULESET_CURRENT_VERSION.to_string() RULESET_CURRENT_VERSION.to_string()
} }
// TODO make the return type a Result fn update_rules(&self) -> std::result::Result<Vec<(Regex, String)>, String> {
fn update_rules(&self) -> Vec<(Regex, String)> {
let mut rules = self.rules.clone(); let mut rules = self.rules.clone();
// TODO Optimize that shit
// TODO break categories in different rules // TODO break categories in different rules
for (category, content) in &self.categories { for (from, to) in rules.iter_mut() {
let mut temp_rules: Vec<(Regex, String)> = Vec::new(); let re = Regex::new("%\\D");
for (from, to) in &rules { let from_match = re.is_match(from.as_str());
let from = Regex::new( let to_match = re.is_match(to);
from.to_string() if from_match || to_match {
.replace( for (category, content) in &self.categories {
if from_match {
*from = Regex::new(
from.to_string()
.replace(
format!("%{}", category).as_str(),
format!("[{}]", content).as_str(),
)
.as_str()
);
}
if to_match {
*to = to.to_string().replace(
format!("%{}", category).as_str(), format!("%{}", category).as_str(),
format!("[{}]", content).as_str(), format!("[{}]", content).as_str()
) );
.as_str(), }
); }
let to = to.to_string().replace(
format!("%{}", category).as_str(),
format!("[{}]", content).as_str(),
);
temp_rules.push((from, to));
} }
rules = temp_rules.clone();
} }
rules Ok(rules)
} }
/// Apply list of rules to input /// Apply list of rules to input
@ -337,7 +341,8 @@ impl Settings {
/// let _output = settings.apply(input); /// let _output = settings.apply(input);
/// ``` /// ```
pub fn apply(&self, s: String) -> std::result::Result<String, String> { pub fn apply(&self, s: String) -> std::result::Result<String, String> {
let rules = self.update_rules(); // TODO Add Error handling
let rules = self.update_rules().unwrap();
let mut s = s.clone(); let mut s = s.clone();
debug!("==============================================="); debug!("===============================================");
for (from, to) in rules { for (from, to) in rules {