#[cfg(feature = "alloc")]
use alloc::{borrow::Cow, string::ToString};
use core::fmt::{self, Write};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Text,
Attribute,
Cdata,
}
#[derive(Clone, Copy, Debug)]
pub struct Unescaped<'xml> {
raw: &'xml str,
kind: Kind,
}
impl<'xml> Unescaped<'xml> {
#[must_use]
pub const fn from_text(raw: &'xml str) -> Self {
Self { raw, kind: Kind::Text }
}
#[must_use]
pub const fn from_attribute_value(raw: &'xml str) -> Self {
Self {
raw,
kind: Kind::Attribute,
}
}
pub(crate) const fn from_cdata(raw: &'xml str) -> Self {
Self { raw, kind: Kind::Cdata }
}
#[must_use]
pub const fn raw(&self) -> &'xml str {
self.raw
}
#[must_use]
pub fn needs_decoding(&self) -> bool {
self.raw.bytes().any(|c| self.is_special(c))
}
#[cfg(feature = "alloc")]
#[must_use]
pub fn to_cow(&self) -> Cow<'xml, str> {
if self.needs_decoding() {
Cow::Owned(self.to_string())
} else {
Cow::Borrowed(self.raw)
}
}
const fn is_special(&self, c: u8) -> bool {
match self.kind {
Kind::Text => matches!(c, b'&' | b'\r'),
Kind::Attribute => matches!(c, b'&' | b'\r' | b'\n' | b'\t'),
Kind::Cdata => c == b'\r',
}
}
fn decode_reference(rest: &str) -> Option<(char, usize)> {
let len = rest
.bytes()
.position(|c| !(c.is_ascii_alphanumeric() || c == b'#'))?;
if rest.as_bytes()[len] != b';' {
return None;
}
let ch = match &rest[..len] {
"lt" => '<',
"gt" => '>',
"amp" => '&',
"apos" => '\'',
"quot" => '"',
name => {
let number = name.strip_prefix('#')?;
let (digits, radix) = match number.strip_prefix('x') {
Some(hex) => (hex, 16),
None => (number, 10),
};
if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
return None;
}
char::from_u32(u32::from_str_radix(digits, radix).ok()?).filter(|&c| is_xml_char(c))?
}
};
Some((ch, len + 1))
}
}
const fn is_xml_char(c: char) -> bool {
matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..)
}
impl fmt::Display for Unescaped<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let b = self.raw.as_bytes();
let mut start = 0; let mut i = 0;
while i < b.len() {
let c = b[i];
if !self.is_special(c) {
i += 1;
continue;
}
f.write_str(&self.raw[start..i])?;
i += 1;
match c {
b'&' => match Self::decode_reference(&self.raw[i..]) {
Some((ch, len)) => {
f.write_char(ch)?;
i += len;
}
None => f.write_char('&')?,
},
b'\r' => {
if b.get(i) == Some(&b'\n') {
i += 1;
}
f.write_char(if self.kind == Kind::Attribute { ' ' } else { '\n' })?;
}
_ => f.write_char(' ')?,
}
start = i;
}
f.write_str(&self.raw[start..])
}
}
impl PartialEq<str> for Unescaped<'_> {
fn eq(&self, other: &str) -> bool {
struct Matcher<'a> {
rest: &'a str,
}
impl Write for Matcher<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
match self.rest.strip_prefix(s) {
Some(rest) => {
self.rest = rest;
Ok(())
}
None => Err(fmt::Error),
}
}
}
let mut matcher = Matcher { rest: other };
write!(matcher, "{self}").is_ok() && matcher.rest.is_empty()
}
}
impl PartialEq<&str> for Unescaped<'_> {
fn eq(&self, other: &&str) -> bool {
*self == **other
}
}