use crate::options::ConversionOptions;
use std::borrow::Cow;
#[must_use]
pub fn has_uri_scheme(href: &str) -> bool {
let mut bytes = href.bytes();
match bytes.next() {
Some(b) if b.is_ascii_alphabetic() => {}
_ => return false,
}
for b in bytes {
match b {
b':' => return true,
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'-' | b'.' => {}
_ => return false,
}
}
false
}
#[must_use]
pub fn percent_encode_url(url: &str) -> String {
let mut encoded = String::with_capacity(url.len() * 2);
for byte in url.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
encoded.push(byte as char);
}
other => {
encoded.push('%');
let hi = char::from_digit(u32::from(other >> 4), 16)
.unwrap_or('0')
.to_ascii_uppercase();
let lo = char::from_digit(u32::from(other & 0x0f), 16)
.unwrap_or('0')
.to_ascii_uppercase();
encoded.push(hi);
encoded.push(lo);
}
}
}
encoded
}
#[must_use]
pub(super) fn percent_encode_non_ascii(url: &str) -> std::borrow::Cow<'_, str> {
if url.is_ascii() {
return std::borrow::Cow::Borrowed(url);
}
let mut encoded = String::with_capacity(url.len() + 8);
for byte in url.bytes() {
if byte.is_ascii() {
encoded.push(byte as char);
} else {
encoded.push('%');
let hi = char::from_digit(u32::from(byte >> 4), 16)
.unwrap_or('0')
.to_ascii_uppercase();
let lo = char::from_digit(u32::from(byte & 0x0f), 16)
.unwrap_or('0')
.to_ascii_uppercase();
encoded.push(hi);
encoded.push(lo);
}
}
std::borrow::Cow::Owned(encoded)
}
#[must_use]
pub(super) fn parens_are_balanced(href: &str) -> bool {
let mut depth: i32 = 0;
for c in href.chars() {
match c {
'(' => depth += 1,
')' => {
depth -= 1;
if depth < 0 {
return false;
}
}
_ => {}
}
}
depth == 0
}
#[must_use]
pub(super) fn escape_ambiguous_destination_backslashes(dest: &str, title_follows: bool) -> std::borrow::Cow<'_, str> {
if !dest.contains('\\') {
return std::borrow::Cow::Borrowed(dest);
}
let chars: Vec<char> = dest.chars().collect();
let last_index = chars.len() - 1;
let mut escaped = String::with_capacity(dest.len() + 4);
for (index, &c) in chars.iter().enumerate() {
if c == '\\' {
let next_is_punctuation = if index == last_index {
!title_follows
} else {
chars.get(index + 1).is_some_and(char::is_ascii_punctuation)
};
if next_is_punctuation {
escaped.push('\\');
}
escaped.push('\\');
} else {
escaped.push(c);
}
}
std::borrow::Cow::Owned(escaped)
}
pub(super) fn entity_reference_end(bytes: &[u8], amp_index: usize) -> Option<usize> {
const MAX_REFERENCE_NAME_LEN: usize = 32;
let mut index = amp_index + 1;
if bytes.get(index) == Some(&b'#') {
index += 1;
}
let name_start = index;
while index < bytes.len() && bytes[index].is_ascii_alphanumeric() && index - name_start < MAX_REFERENCE_NAME_LEN {
index += 1;
}
if index == name_start {
return None;
}
(bytes.get(index) == Some(&b';')).then_some(index + 1)
}
#[must_use]
pub fn escape_entity_ampersands(text: &str) -> Cow<'_, str> {
if !text.contains('&') {
return Cow::Borrowed(text);
}
let bytes = text.as_bytes();
let mut result = String::with_capacity(text.len());
let mut copied_up_to = 0;
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'&' {
if let Some(reference_end) = entity_reference_end(bytes, index) {
let candidate = &text[index..reference_end];
if html_escape::decode_html_entities(candidate) != candidate {
result.push_str(&text[copied_up_to..index]);
result.push_str("&");
result.push_str(&text[index + 1..reference_end]);
copied_up_to = reference_end;
index = reference_end;
continue;
}
}
}
index += 1;
}
if copied_up_to == 0 {
return Cow::Borrowed(text);
}
result.push_str(&text[copied_up_to..]);
Cow::Owned(result)
}
#[must_use]
pub fn escape_markdown_title(text: &str) -> std::borrow::Cow<'_, str> {
let text = escape_entity_ampersands(text);
if !text.contains('\\') && !text.contains('"') {
return text;
}
std::borrow::Cow::Owned(text.replace('\\', "\\\\").replace('"', "\\\""))
}
fn push_angle_wrapped_destination(output: &mut String, dest: &str) {
output.push('<');
for c in dest.chars() {
match c {
'\\' => output.push_str("\\\\"),
'<' => output.push_str("\\<"),
'>' => output.push_str("\\>"),
'\n' => output.push(' '),
other => output.push(other),
}
}
output.push('>');
}
pub fn append_url_destination(
output: &mut String,
dest: &str,
url_escape_style: crate::options::validation::UrlEscapeStyle,
title_follows: bool,
) {
if dest.is_empty() {
output.push_str("<>");
return;
}
if url_escape_style == crate::options::validation::UrlEscapeStyle::Percent {
let encoded = percent_encode_url(dest);
output.push_str(&encoded);
return;
}
let dest = if dest.starts_with('#') {
std::borrow::Cow::Borrowed(dest)
} else {
percent_encode_non_ascii(dest)
};
let dest = dest.as_ref();
let dest = escape_entity_ampersands(dest);
let dest = dest.as_ref();
if dest.contains(' ') || dest.contains('\n') {
push_angle_wrapped_destination(output, dest);
} else if parens_are_balanced(dest) {
output.push_str(&escape_ambiguous_destination_backslashes(dest, title_follows));
} else {
let dest = dest.replace('\\', "\\\\");
let escaped_dest = dest.replace('(', "\\(").replace(')', "\\)");
output.push_str(&escaped_dest);
}
}
#[derive(Clone, Copy)]
pub struct MarkdownLink<'a> {
pub label: &'a str,
pub href: &'a str,
pub title: Option<&'a str>,
pub raw_text: &'a str,
}
pub fn append_markdown_link(
output: &mut String,
link: &MarkdownLink<'_>,
options: &ConversionOptions,
reference_collector: Option<&crate::converter::reference_collector::ReferenceCollectorHandle>,
) {
let MarkdownLink {
label,
href,
title,
raw_text,
} = *link;
if options.link_style == crate::options::validation::LinkStyle::Reference && !href.is_empty() {
if let Some(collector) = reference_collector {
let ref_num = collector.borrow_mut().get_or_insert(href, title);
output.push('[');
output.push_str(label);
output.push_str("][");
output.push_str(&ref_num.to_string());
output.push(']');
return;
}
}
output.push('[');
output.push_str(label);
output.push_str("](");
let title_follows = title.is_some() || (options.default_title && raw_text == href);
append_url_destination(output, href, options.url_escape_style, title_follows);
if let Some(title_text) = title {
output.push_str(" \"");
output.push_str(&escape_markdown_title(title_text));
output.push('"');
} else if options.default_title && raw_text == href {
output.push_str(" \"");
output.push_str(&escape_markdown_title(href));
output.push('"');
}
output.push(')');
}