#[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(name: &str) -> Option<char> {
match name {
"lt" => Some('<'),
"gt" => Some('>'),
"amp" => Some('&'),
"apos" => Some('\''),
"quot" => Some('"'),
_ => {
let number = name.strip_prefix('#')?;
let code = match number.strip_prefix('x') {
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
None => number.parse().ok()?,
};
char::from_u32(code)
}
}
}
}
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'&' => {
let semicolon = b[i..b.len().min(i + 9)]
.iter()
.position(|&c| c == b';');
match semicolon.and_then(|len| Self::decode_reference(&self.raw[i..i + len]).map(|ch| (ch, len))) {
Some((ch, len)) => {
f.write_char(ch)?;
i += len + 1;
}
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
}
}