mathml/
regexes.rs

1/// We need to apply some replacements to account for things like
2/// https://www.tutorialspoint.com/mathml/mathml_greek_letters.htm
3/// Or else the xml parser fails :(
4/// Replaces &$STRING; with $STRING
5
6macro_rules! replace {
7    ($($e:ident),*) => {{
8    let mut temp_vec = Vec::new();
9            $(
10               temp_vec.push(replace_one(format!("&{};", stringify!($e)), stringify!($e)));
11            )*
12            move |x| temp_vec.iter().fold(x,|acc,next|next(acc))
13           }
14    }
15
16}
17fn replace_one(from: String, to: &'static str) -> impl Fn(String) -> String + 'static {
18    move |x: String| x.replace(&from, format!("$FIXED_{}", to).as_ref())
19}
20/// This function exists because the underlying XML parser will crash with certain &tag; expressions
21/// We just replace them with $FIXED_tag as text
22pub fn sanitize_xml(x: &str) -> String {
23    let replacer = replace! {tau,alpha,beta,gamma,
24    delta,epsilon,zeta,eta,theta,iota,kappa,lambda,mu,nu,xi,
25    omicron,pi,rho,sigma,upsilon,phi,chi,psi,omega};
26    replacer(x.to_owned())
27}
28#[cfg(test)]
29mod test {
30    use super::*;
31    #[test]
32    fn test_replace() {
33        let test = r#"<cn type="constant">  &tau;&bla; </cn>"#;
34        let replacer = replace! {tau,bla};
35        let output = replacer(test.to_owned());
36        assert_eq!(
37            output,
38            test.replace("&tau;", "$FIXED_tau")
39                .replace("&bla;", "$FIXED_bla")
40        )
41    }
42}