roxml 0.4.2

Read-only, zero-copy, lazy XML reader for no_std environments, without allocation
Documentation
// Copyright © 2026 Stephan Kunz
//! Attribute types `XmlAttribute` and `XmlAttributes`.

use core::{fmt, ops::Range};

use crate::{helpers::split_qname, unescaped::Unescaped};

/// A single `name="value"` pair inside an element's opening tag.
#[derive(Clone)]
pub struct XmlAttribute<'xml> {
	xml_text: &'xml str,
	name: Range<usize>,
	value: Range<usize>,
}

impl<'xml> XmlAttribute<'xml> {
	/// Attribute name as written, including a namespace prefix.
	#[must_use]
	pub fn name(&self) -> &'xml str {
		&self.xml_text[self.name.clone()]
	}

	/// Namespace prefix of the name, or `None` if there is none.
	///
	/// For a namespace declaration `xmlns:p="…"` the prefix is `xmlns`.
	#[must_use]
	pub fn prefix(&self) -> Option<&'xml str> {
		split_qname(self.name()).0
	}

	/// Name without its namespace prefix.
	#[must_use]
	pub fn local_name(&self) -> &'xml str {
		split_qname(self.name()).1
	}

	/// Raw attribute value as written, without surrounding quotes. Entity
	/// references such as `&amp;` are not decoded, use
	/// [`unescaped_value`](Self::unescaped_value) for that.
	#[must_use]
	pub fn value(&self) -> &'xml str {
		&self.xml_text[self.value.clone()]
	}

	/// Attribute value with entity references decoded and white space
	/// normalized, see [`Unescaped`].
	///
	/// # Examples
	/// ```
	/// use roxml::XmlReader;
	///
	/// let reader = XmlReader::parse(r#"<Script code="x &lt; 3 &amp;&amp; y"/>"#);
	/// let root = reader.root_element()?;
	/// let code = root.attributes().find(|a| a.name() == "code").unwrap();
	/// assert_eq!(code.value(), "x &lt; 3 &amp;&amp; y");
	/// assert_eq!(code.unescaped_value(), "x < 3 && y");
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn unescaped_value(&self) -> Unescaped<'xml> {
		Unescaped::from_attribute_value(self.value())
	}
}

// ── iterators ────────────────────────────────────────────────────────────────

/// Iterator over attributes in an element's opening tag.
#[derive(Clone)]
pub struct XmlAttributes<'xml> {
	pub(crate) xml_text: &'xml str,
	pub(crate) pos: usize,
	pub(crate) end: usize,
}

impl<'xml> Iterator for XmlAttributes<'xml> {
	type Item = XmlAttribute<'xml>;

	fn next(&mut self) -> Option<Self::Item> {
		let b = self.xml_text.as_bytes();
		// Skip whitespace
		while self.pos < self.end && matches!(b[self.pos], b' ' | b'\t' | b'\n' | b'\r') {
			self.pos += 1;
		}
		if self.pos >= self.end || matches!(b[self.pos], b'/' | b'>') {
			return None;
		}
		// Name
		let name_start = self.pos;
		while self.pos < self.end && !matches!(b[self.pos], b'=' | b' ' | b'\t' | b'\n' | b'\r') {
			self.pos += 1;
		}
		let name_end = self.pos;
		// Skip whitespace, then '=' has to follow
		while self.pos < self.end && matches!(b[self.pos], b' ' | b'\t' | b'\n' | b'\r') {
			self.pos += 1;
		}
		if self.pos >= self.end || b[self.pos] != b'=' {
			return None;
		}
		self.pos += 1; // skip '='
		// Skip whitespace
		while self.pos < self.end && matches!(b[self.pos], b' ' | b'\t' | b'\n' | b'\r') {
			self.pos += 1;
		}
		if self.pos >= self.end {
			return None;
		}
		let quote = b[self.pos];
		if quote != b'"' && quote != b'\'' {
			return None;
		}
		self.pos += 1; // skip opening quote
		let val_start = self.pos;
		while self.pos < self.end && b[self.pos] != quote {
			self.pos += 1;
		}
		if self.pos >= self.end {
			return None;
		}
		let val_end = self.pos;
		self.pos += 1; // skip closing quote
		Some(XmlAttribute {
			xml_text: self.xml_text,
			name: name_start..name_end,
			value: val_start..val_end,
		})
	}
}

impl fmt::Debug for XmlAttribute<'_> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("XmlAttribute")
			.field("name", &self.name())
			.field("value", &self.value())
			.finish()
	}
}

impl fmt::Debug for XmlAttributes<'_> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("XmlAttributes")
			.field(
				"rest",
				&self
					.xml_text
					.get(self.pos..self.end)
					.unwrap_or_default(),
			)
			.finish()
	}
}