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