roxml 0.4.1

Read-only, zero-copy, lazy XML reader for no_std environments, without allocation
Documentation
// Copyright © 2026 Stephan Kunz
//! Decoding of entity references: `Unescaped`.

#[cfg(feature = "alloc")]
use alloc::{borrow::Cow, string::ToString};
use core::fmt::{self, Write};

/// What a raw slice is and therefore how it is decoded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
	/// Character data: entity references are decoded, line ends normalized.
	Text,
	/// Attribute value: like `Text`, plus literal white space becomes a space.
	Attribute,
	/// CDATA section content: only line ends are normalized.
	Cdata,
}

/// The decoded form of a raw text or attribute value, computed on demand
/// without allocation.
///
/// Decoding replaces
/// - the predefined entities `<` `>` `&` `'` `"`,
/// - character references `A` and `A`,
/// - line ends `\r\n` and `\r` by `\n`,
/// - in attribute values additionally each literal tab, line feed and carriage
///   return by a space (attribute value normalization of the XML specification).
///
/// An unknown entity, a reference without `;` or one to a character that XML
/// does not allow, e.g. `�`, is kept as written. Character references
/// consist of digits only, any number of them. Content of CDATA sections only gets its line ends
/// normalized.
///
/// Obtain an `Unescaped` from [`XmlText::unescaped`](crate::XmlText::unescaped) or
/// [`XmlAttribute::unescaped_value`](crate::XmlAttribute::unescaped_value), or
/// wrap any raw slice with [`from_text`](Self::from_text) or
/// [`from_attribute_value`](Self::from_attribute_value).
///
/// Use it through [`Display`](core::fmt::Display), for example with `write!`
/// into a buffer or with `to_string()`, compare it with a `&str`, or, with
/// feature `alloc`, convert it with [`to_cow`](Self::to_cow).
///
/// # Examples
/// ```
/// use roxml::Unescaped;
///
/// let value = Unescaped::from_attribute_value("x < 3 && y > 4");
/// assert_eq!(value, "x < 3 && y > 4");
/// assert_eq!(value.to_string(), "x < 3 && y > 4");
/// assert_eq!(value.raw(), "x &lt; 3 &amp;&amp; y &#x3E; 4");
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Unescaped<'xml> {
	raw: &'xml str,
	kind: Kind,
}

impl<'xml> Unescaped<'xml> {
	/// Wraps raw character data, as found between tags.
	#[must_use]
	pub const fn from_text(raw: &'xml str) -> Self {
		Self { raw, kind: Kind::Text }
	}

	/// Wraps a raw attribute value, without its quotes.
	#[must_use]
	pub const fn from_attribute_value(raw: &'xml str) -> Self {
		Self {
			raw,
			kind: Kind::Attribute,
		}
	}

	/// Wraps the content of a CDATA section, without its markers.
	pub(crate) const fn from_cdata(raw: &'xml str) -> Self {
		Self { raw, kind: Kind::Cdata }
	}

	/// The raw slice as written in the source.
	#[must_use]
	pub const fn raw(&self) -> &'xml str {
		self.raw
	}

	/// Whether the decoded form differs from the raw slice.
	///
	/// If not, [`raw`](Self::raw) can be used directly without copying.
	#[must_use]
	pub fn needs_decoding(&self) -> bool {
		self.raw.bytes().any(|c| self.is_special(c))
	}

	/// The decoded form, borrowed from the source if nothing needs decoding.
	///
	/// # Examples
	/// ```
	/// use std::borrow::Cow;
	/// use roxml::Unescaped;
	///
	/// assert!(matches!(Unescaped::from_text("plain").to_cow(), Cow::Borrowed("plain")));
	/// assert_eq!(Unescaped::from_text("a &amp; b").to_cow(), "a & b");
	/// ```
	#[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',
		}
	}

	/// Decode the entity or character reference at the start of `rest`, the
	/// text after `&`, e.g. `amp;` or `#x41;`. Returns the character and the
	/// length of the reference including its `;`.
	///
	/// The reference runs over ASCII letters, digits and `#`, so each call
	/// only looks at bytes up to the next `&` and decoding stays linear.
	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),
				};
				// `from_str_radix` alone would also accept a leading `+`
				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))
	}
}

/// Whether XML allows `c` in a document (production `Char` of the XML specification).
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; // start of the not yet written part of `raw`
		let mut i = 0;
		while i < b.len() {
			let c = b[i];
			if !self.is_special(c) {
				i += 1;
				continue;
			}
			// all special bytes are ASCII, so slicing at them is valid UTF-8
			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' })?;
				}
				// `\n` and `\t` are only special in attribute values
				_ => f.write_char(' ')?,
			}
			start = i;
		}
		f.write_str(&self.raw[start..])
	}
}

/// Compares the decoded form with `other`, without allocation.
impl PartialEq<str> for Unescaped<'_> {
	fn eq(&self, other: &str) -> bool {
		/// Consumes `rest` while the written pieces match it.
		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
	}
}