use std::borrow::Cow;
pub fn strip_inline_code(line: &str) -> Cow<'_, str> {
if !line.contains('`') {
return Cow::Borrowed(line);
}
let bytes = line.as_bytes();
let len = bytes.len();
let mut result = line.as_bytes().to_vec();
let mut i = 0;
while i < len {
if bytes[i] == b'`' {
let start = i;
let mut backtick_count = 0;
while i < len && bytes[i] == b'`' {
backtick_count += 1;
i += 1;
}
let content_start = i;
let mut found_close = false;
while i < len {
if bytes[i] == b'`' {
let mut close_count = 0;
while i < len && bytes[i] == b'`' {
close_count += 1;
i += 1;
}
if close_count == backtick_count {
for b in &mut result[start..i] {
*b = b' ';
}
found_close = true;
break;
}
} else {
i += 1;
}
}
if !found_close {
i = content_start;
}
} else {
i += 1;
}
}
Cow::Owned(unsafe { String::from_utf8_unchecked(result) })
}
pub(crate) fn is_comment_fence(line: &str) -> bool {
line.trim() == "%%"
}
pub fn strip_inline_comments(line: &str) -> Cow<'_, str> {
if !line.contains("%%") {
return Cow::Borrowed(line);
}
let bytes = line.as_bytes();
let len = bytes.len();
let mut result = bytes.to_vec();
let mut i = 0;
while i + 1 < len {
if bytes[i] == b'%' && bytes[i + 1] == b'%' {
let open = i;
i += 2;
if line[i..].trim().is_empty() {
break;
}
let mut found_close = false;
while i + 1 < len {
if bytes[i] == b'%' && bytes[i + 1] == b'%' {
for b in &mut result[open..i + 2] {
*b = b' ';
}
i += 2;
found_close = true;
break;
}
i += 1;
}
if !found_close {
i = open + 2;
}
} else {
i += 1;
}
}
if result == bytes {
Cow::Borrowed(line)
} else {
Cow::Owned(unsafe { String::from_utf8_unchecked(result) })
}
}