pub(crate) fn strip_cfg_test_blocks(src: &str) -> String {
const MARKER: &str = "#[cfg(test)]";
let mut result = String::new();
let mut rest = src;
loop {
let Some(marker_pos) = rest.find(MARKER) else {
result.push_str(rest);
break;
};
result.push_str(&rest[..marker_pos]);
let after_marker = &rest[marker_pos + MARKER.len()..];
let Some(brace_pos) = after_marker.find('{') else {
rest = after_marker;
continue;
};
let bytes = after_marker.as_bytes();
let mut depth: i32 = 0;
let mut i = brace_pos;
let mut end = after_marker.len();
while i < bytes.len() {
match bytes[i] {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
end = i + 1;
break;
}
}
_ => {}
}
i += 1;
}
rest = &after_marker[end..];
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_a_single_cfg_test_mod_block_entirely() {
let src = "fn production() {}\n\n#[cfg(test)]\nmod tests {\n fn f() { thread::spawn(|| {}); }\n}\n";
let stripped = strip_cfg_test_blocks(src);
assert!(!stripped.contains("thread::spawn"));
assert!(stripped.contains("fn production()"));
}
#[test]
fn leaves_production_code_outside_any_cfg_test_block_untouched() {
let src = "fn production() { thread::spawn(|| {}); }\n";
let stripped = strip_cfg_test_blocks(src);
assert!(stripped.contains("thread::spawn"));
}
#[test]
fn handles_nested_braces_inside_the_stripped_block() {
let src = "#[cfg(test)]\nmod tests {\n fn f() { if true { thread::spawn(|| {}); } }\n}\nfn after() {}\n";
let stripped = strip_cfg_test_blocks(src);
assert!(!stripped.contains("thread::spawn"));
assert!(stripped.contains("fn after()"));
}
}