roxml 0.4.2

Read-only, zero-copy, lazy XML reader for no_std environments, without allocation
Documentation
// Copyright © 2026 Stephan Kunz
//! Implementation of the `XmlReader`.

use core::fmt;

use crate::{
	epilog::XmlEpilog,
	error::Error,
	helpers::{bom_len, check_root_at, find_bytes, is_declaration_at, skip_misc},
	prolog::XmlProlog,
	xml_element::XmlElement,
};

/// Lazily parses XML from a borrowed source string.
///
/// No DOM tree is built. Navigation is done on demand through [`XmlElement`]
/// and the section iterators [`XmlProlog`] and [`XmlEpilog`]. Everything
/// returned borrows from the source string.
///
/// # Examples
/// ```
/// use roxml::prelude::*;
///
/// let reader = XmlReader::parse(r#"<config><port nr="8080"/></config>"#);
/// let root = reader.root_element()?;
/// let port = root
///     .children()
///     .find_map(|node| match node {
///         BodyNode::Element(e) if e.tag_name() == "port" => e.attribute("nr"),
///         _ => None,
///     });
/// assert_eq!(port, Some("8080"));
/// # Ok::<(), roxml::Error>(())
/// ```
#[derive(Clone, Copy)]
pub struct XmlReader<'xml> {
	xml_text: &'xml str,
}

impl<'xml> XmlReader<'xml> {
	/// Wraps `xml_doc` for lazy parsing. No work is done here; in particular
	/// the document is not checked, see [`root_element`](Self::root_element).
	#[must_use]
	pub fn parse(xml_doc: &'xml str) -> XmlReader<'xml> {
		XmlReader { xml_text: xml_doc }
	}

	/// Returns an iterator over the document prolog (nodes before the root
	/// element): Declaration, Doctype, Comment, and PI.
	///
	/// See [`XmlProlog`] for an example.
	#[must_use]
	pub fn prolog(&self) -> XmlProlog<'xml> {
		XmlProlog {
			xml_text: self.xml_text,
			pos: bom_len(self.xml_text),
		}
	}

	/// Returns the document's root element after checking the structure of the
	/// whole document.
	///
	/// A leading byte order mark, the XML declaration, DOCTYPE, comments and
	/// processing instructions that precede the root are skipped. The root
	/// element has no siblings; the nodes following it are available through
	/// [`epilog`](Self::epilog).
	///
	/// The check covers the document structure, not every rule of the XML
	/// specification. Detected are:
	/// - character data before or after the root element,
	/// - markup other than comments and processing instructions after the root element,
	/// - unclosed tags, comments, processing instructions, CDATA sections and DOCTYPE declarations,
	/// - close tags that do not match their open tag,
	/// - empty tag names, tag names containing a quote (`"` or `'`) and a
	///   DOCTYPE inside an element,
	/// - malformed attributes in open tags: a missing `=`, a missing or unquoted
	///   value, a missing whitespace before an attribute, or anything else than
	///   attributes between the tag name and `>` or `/>`,
	/// - an XML declaration anywhere but at the very start, and other processing
	///   instructions with the reserved target `xml` in any case.
	///
	/// Not detected are
	/// - other invalid characters in names, e.g. `<1a/>`,
	/// - duplicate attributes,
	/// - undefined entities,
	/// - a repeated DOCTYPE,
	/// - `>` and `]]>` in character data,
	/// - `--` inside comments,
	/// - `<` inside attribute values,
	/// - characters that XML does not allow.
	///
	/// The check scans the whole document, so call this once and keep the
	/// returned element.
	///
	/// # Errors
	/// - [`Error::NoRoot`] – source contains no element.
	/// - [`Error::MalformedXml`] – the document structure is broken as listed above.
	/// - [`Error::TooDeep`] – elements are nested deeper than [`MAX_DEPTH`](crate::MAX_DEPTH).
	///
	/// # Examples
	/// ```
	/// use roxml::{Error, XmlReader};
	///
	/// let xml = r#"<?xml version="1.0"?><!-- data --><root/>"#;
	/// assert_eq!(XmlReader::parse(xml).root_element()?.tag_name(), "root");
	///
	/// assert_eq!(XmlReader::parse("<!-- empty -->").root_element().err(), Some(Error::NoRoot));
	/// assert_eq!(XmlReader::parse("<a><b></a>").root_element().err(), Some(Error::MalformedXml));
	/// assert_eq!(XmlReader::parse("<a/><b/>").root_element().err(), Some(Error::MalformedXml));
	/// # Ok::<(), roxml::Error>(())
	/// ```
	pub fn root_element(&self) -> Result<XmlElement<'xml>, Error> {
		let len = self.xml_text.len();
		let b = self.xml_text.as_bytes();
		let mut start = bom_len(self.xml_text);
		// the declaration is only allowed at the very start
		if is_declaration_at(b, start) {
			start = find_bytes(b, start + 2, b"?>").ok_or(Error::MalformedXml)? + 2;
		}
		let pos = skip_misc(self.xml_text, start, true)?;
		if pos >= len {
			return Err(Error::NoRoot);
		}
		let root = check_root_at(self.xml_text, pos)?;
		if skip_misc(self.xml_text, root.range().end, false)? < len {
			return Err(Error::MalformedXml);
		}
		Ok(root)
	}

	/// Returns an iterator over the document epilog (comments and processing
	/// instructions after the root element). Whitespace is silently skipped.
	/// Any other content stops the iterator. If the document has no valid
	/// root element, the iterator is empty.
	///
	/// This locates the root element first, see [`root_element`](Self::root_element)
	/// for the cost. See [`XmlEpilog`] for an example.
	#[must_use]
	pub fn epilog(&self) -> XmlEpilog<'xml> {
		let start = self
			.root_element()
			.map_or(self.xml_text.len(), |root| root.range().end);
		XmlEpilog {
			xml_text: self.xml_text,
			pos: start,
		}
	}
}

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