use std::borrow::Cow;
pub const RULE_MARKER_OPEN: &str = "<!-- rule:";
const RULE_MARKER_CLOSE: &str = " -->";
pub fn marker_id(line: &str) -> Option<&str> {
let id = line
.trim()
.strip_prefix(RULE_MARKER_OPEN)?
.strip_suffix(RULE_MARKER_CLOSE)?;
let valid = id.split(['-', '/']).all(|word| {
!word.is_empty() && word.bytes().all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9'))
});
valid.then_some(id)
}
fn outside_fences(text: &str) -> impl Iterator<Item = (&str, bool)> {
let mut fenced = false;
text.split_inclusive('\n').map(move |line| {
let trimmed = line.trim_start();
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
fenced = !fenced;
(line, false)
} else {
(line, !fenced)
}
})
}
pub fn rule_ids(text: &str) -> Vec<&str> {
outside_fences(text)
.filter(|(_, outside)| *outside)
.filter_map(|(line, _)| marker_id(line))
.collect()
}
pub fn malformed_markers(text: &str) -> Vec<&str> {
outside_fences(text)
.filter(|(line, outside)| *outside && line.trim_start().starts_with(RULE_MARKER_OPEN))
.filter(|(line, _)| marker_id(line).is_none())
.map(|(line, _)| line.trim())
.collect()
}
pub fn strip_rule_markers(text: &str) -> Cow<'_, str> {
if !text.contains(RULE_MARKER_OPEN) {
return Cow::Borrowed(text);
}
Cow::Owned(
outside_fences(text)
.filter(|(line, outside)| !(*outside && marker_id(line).is_some()))
.map(|(line, _)| line)
.collect(),
)
}
#[cfg(test)]
#[path = "rule_marker_tests.rs"]
mod tests;