pub fn replace_underscores(text: &mut String) {
let mut matches = vec![];
let mut prev_colon = false;
for (idx, ch) in text.char_indices() {
if ch == '_' {
if idx > 0 && !prev_colon {
matches.push(idx);
}
}
prev_colon = ch == ':';
}
for idx in matches {
text.replace_range(idx..idx + 1, "-");
}
}
#[test]
fn test_replace_underscores() {
macro_rules! check {
($input:expr, $expected:expr,) => {
check!($input, $expected)
};
($input:expr, $expected:expr) => {{
let mut text = str!($input);
replace_underscores(&mut text);
assert_eq!(
&text, $expected,
"Underscore replacement didn't match expected (input: '{}')",
$input,
);
}};
}
check!("", "");
check!("a", "a");
check!("_a", "_a");
check!("a_", "a-");
check!("page-name", "page-name");
check!("_template", "_template");
check!("__template", "_-template");
check!("_template_", "_template-");
check!("_special_page", "_special-page");
check!("_special__page", "_special--page");
check!("fragment:page-name", "fragment:page-name");
check!("fragment:_template", "fragment:_template");
check!("fragment:__template", "fragment:_-template");
check!("fragment:_template_", "fragment:_template-");
check!("fragment:_special_page", "fragment:_special-page");
check!("fragment:_special__page", "fragment:_special--page");
check!("_default:page-name", "_default:page-name");
check!("_default:_template", "_default:_template");
check!("_default:__template", "_default:_-template");
check!("_default:_template_", "_default:_template-");
check!("_default:_special_page", "_default:_special-page");
check!("_default:_special__page", "_default:_special--page");
check!(
"protected:fragment:page-name",
"protected:fragment:page-name",
);
check!(
"protected:fragment:_template",
"protected:fragment:_template",
);
check!(
"protected:fragment:__template",
"protected:fragment:_-template",
);
check!(
"protected:fragment:_template_",
"protected:fragment:_template-",
);
check!(
"protected:fragment:_special_page",
"protected:fragment:_special-page",
);
check!(
"protected:fragment:_special__page",
"protected:fragment:_special--page",
);
}