use regex::Regex;
use std::{borrow::Cow, convert::Infallible};
use super::TransformField;
use crate::{action::transform::result::TransformResult, error::BadRegexError};
pub const HTML_TAG_RE: &str = "<[^>]*>";
#[derive(Debug)]
pub struct Replace {
re: Regex,
with: String,
}
impl Replace {
pub fn new(re: &str, with: String) -> Result<Self, BadRegexError> {
Ok(Self {
re: Regex::new(re)?,
with,
})
}
}
impl TransformField for Replace {
type Err = Infallible;
fn transform_field(&self, old_val: Option<&str>) -> Result<TransformResult<String>, Self::Err> {
Ok(TransformResult::New(old_val.map(|old| {
self.re.replace_all(old, &self.with).into_owned()
})))
}
}
impl Replace {
#[must_use]
pub fn replace<'a>(&self, text: &'a str) -> Cow<'a, str> {
self.re.replace_all(text, &self.with)
}
}