#[must_use]
pub fn preprocess(raw_input: &str) -> String {
trim_math(raw_input).to_string()
}
fn trim_math(input: &str) -> &str {
let start = input.len() - input.trim_start().len();
let body = &input[start..];
let kept = body.trim_end();
if kept.len() == body.len() || !ends_with_odd_backslash(kept) {
return &input[start..start + kept.len()];
}
if body.as_bytes().get(kept.len()) == Some(&b' ') {
&input[start..start + kept.len() + 1]
} else {
&input[start..start + kept.len()]
}
}
fn ends_with_odd_backslash(s: &str) -> bool {
let bytes = s.as_bytes();
let mut n = 0usize;
while n < bytes.len() && bytes[bytes.len() - 1 - n] == b'\\' {
n += 1;
}
n % 2 == 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trailing_period_kept() {
assert_eq!(preprocess("x^2."), "x^2.");
}
#[test]
fn rewrites_are_gone() {
for s in [
r"{a \over b}",
r"{n \choose k}",
r"{\rm x}",
r"{ (}",
r"{[}",
r"\mbox{x}",
r"\left(\frac{1}{2}\right)",
r"\tfrac{a}{b}",
r"a\,b",
] {
assert_eq!(preprocess(s), s);
}
}
#[test]
fn control_space_survives_trim() {
assert_eq!(preprocess(r"\ "), r"\ ");
assert_eq!(preprocess(r" \ "), r"\ ");
assert_eq!(preprocess("\\ %@QJXi"), "\\ %@QJXi");
assert_eq!(preprocess(r"\\ "), r"\\");
assert_eq!(preprocess(r"\\\ "), r"\\\ ");
}
#[test]
fn empty() {
assert_eq!(preprocess(" "), "");
assert!(matches!(
crate::parse(""),
Err(crate::ParseError::Malformed(_))
));
assert!(matches!(
crate::parse(" "),
Err(crate::ParseError::Malformed(_))
));
}
}