use std::borrow::Cow;
const HTML4_ENTITIES: &str = include_str!("html4-entities.txt");
pub fn e(input: &str) -> String {
e_with_double_encode(input, true)
}
pub fn e_with_double_encode(input: &str, double_encode: bool) -> String {
let mut output = String::with_capacity(input.len());
let _: Result<(), std::convert::Infallible> = escape_parts(input, double_encode, |part| {
output.push_str(part);
Ok(())
});
output
}
pub(crate) fn escape_parts<E>(
input: &str,
double_encode: bool,
write: impl FnMut(&str) -> Result<(), E>,
) -> Result<(), E> {
escape_parts_for(input, double_encode, &['&', '<', '>', '"', '\''], write)
}
pub(crate) fn escape_attribute_parts<E>(
input: &str,
write: impl FnMut(&str) -> Result<(), E>,
) -> Result<(), E> {
escape_parts_for(input, false, &['&', '<', '>', '"'], write)
}
fn escape_parts_for<E>(
input: &str,
double_encode: bool,
special_characters: &[char],
mut write: impl FnMut(&str) -> Result<(), E>,
) -> Result<(), E> {
let mut rest = input;
while let Some(index) = rest.find(special_characters) {
let special = rest.as_bytes()[index];
if special == b'&'
&& !double_encode
&& let Some(len) = entity_len(&rest[index + 1..])
{
let (entity, remaining) = rest.split_at(index + 1 + len);
write(entity)?;
rest = remaining;
continue;
}
if index != 0 {
write(&rest[..index])?;
}
rest = &rest[index + 1..];
write(match special {
b'&' => "&",
b'<' => "<",
b'>' => ">",
b'"' => """,
_ => "'",
})?;
}
write(rest)
}
impl crate::value::Value<'_> {
pub(crate) fn write_text(
&self,
escape: Option<bool>,
mut write: impl FnMut(&str) -> crate::error::Result<()>,
) -> crate::error::Result<()> {
let display;
let text = match self {
Self::Str(text) | Self::Html(text) => text.as_ref(),
Self::Json(serde_json::Value::String(text)) => text.as_str(),
Self::Object(object) if let Some(text) = object.display_text() => text,
_ => {
display = self.display()?;
&display
}
};
match escape {
Some(double_encode) => escape_parts(text, double_encode, write),
None => write(text),
}
}
}
pub fn escape_html_bytes(input: &[u8], double_encode: bool) -> String {
e_with_double_encode(
&decode_utf8(input, Some('\u{fffd}')).unwrap_or_default(),
double_encode,
)
}
fn entity_len(rest: &str) -> Option<usize> {
let end = rest
.bytes()
.position(|byte| !byte.is_ascii_alphanumeric() && byte != b'#')?;
if rest.as_bytes()[end] != b';' {
return None;
}
let entity = &rest[..end];
let valid = match entity.strip_prefix('#') {
Some(number) => {
let (digits, radix) = match number.strip_prefix(['x', 'X']) {
Some(hex) => (hex, 16),
None => (number, 10),
};
!digits.is_empty()
&& u32::from_str_radix(digits, radix).is_ok_and(|value| value <= 0x10ffff)
}
None => HTML4_ENTITIES.lines().any(|name| name == entity),
};
valid.then_some(end + 1)
}
pub(super) fn decode_utf8(input: &[u8], replacement: Option<char>) -> Option<Cow<'_, str>> {
if let Ok(valid) = std::str::from_utf8(input) {
return Some(Cow::Borrowed(valid));
}
let replacement = replacement?;
let mut output = String::with_capacity(input.len());
let mut rest = input;
loop {
match std::str::from_utf8(rest) {
Ok(valid) => {
output.push_str(valid);
return Some(Cow::Owned(output));
}
Err(error) => {
let (valid, invalid) = rest.split_at(error.valid_up_to());
output.push_str(std::str::from_utf8(valid).ok()?);
let width = match invalid[0] {
0xc2..=0xdf => 2,
0xe0..=0xef => 3,
0xf0..=0xf4 => 4,
_ => 1,
};
let continuation = invalid[1..]
.iter()
.take(width - 1)
.take_while(|byte| **byte & 0xc0 == 0x80)
.count();
if replacement != '\0' {
output.push(replacement);
}
rest = &invalid[1 + continuation..];
}
}
}
}