roxml 0.4.0

Read-only, zero-copy, lazy XML reader for no_std environments, without allocation
Documentation
// Copyright © 2026 Stephan Kunz
//! Prolog section types: `PrologNode`, `PrologComment`, `PrologPI`, `XmlProlog`.

use core::ops::Range;

use crate::{
	helpers::{
		bom_len, comment_text, find_bytes, find_doctype_end, is_declaration_at, is_doctype_at, is_reserved_pi_at,
		pi_content, pi_target, skip_whitespace,
	},
	xml_declaration::XmlDeclaration,
	xml_doctype::XmlDoctype,
};

/// A node that may appear in the document prolog (before the root element).
pub enum PrologNode<'xml> {
	/// The XML declaration: `<?xml … ?>`.
	Declaration(XmlDeclaration<'xml>),
	/// A DOCTYPE declaration: `<!DOCTYPE … >`.
	Doctype(XmlDoctype<'xml>),
	/// A comment: `<!-- … -->`.
	Comment(PrologComment<'xml>),
	/// A processing instruction other than the XML declaration: `<?target content?>`.
	PI(PrologPI<'xml>),
}

/// A comment in the document prolog.
#[derive(Clone)]
pub struct PrologComment<'xml> {
	xml_text: &'xml str,
	range: Range<usize>,
}

impl<'xml> PrologComment<'xml> {
	/// Comment body with `<!--` and `-->` stripped.
	#[must_use]
	pub fn text(&self) -> &'xml str {
		comment_text(&self.xml_text[self.range.clone()])
	}

	/// Byte range of this node in the source text.
	#[must_use]
	pub fn range(&self) -> Range<usize> {
		self.range.clone()
	}
}

/// A processing instruction in the document prolog (not the XML declaration).
#[derive(Clone)]
pub struct PrologPI<'xml> {
	xml_text: &'xml str,
	range: Range<usize>,
}

impl<'xml> PrologPI<'xml> {
	/// PI target name (the token immediately after `<?`).
	#[must_use]
	pub fn target(&self) -> &'xml str {
		pi_target(self.xml_text, &self.range)
	}

	/// PI content: everything after the target and its trailing whitespace,
	/// up to (but not including) `?>`.
	#[must_use]
	pub fn content(&self) -> &'xml str {
		pi_content(self.xml_text, &self.range)
	}

	/// Byte range of this node in the source text.
	#[must_use]
	pub fn range(&self) -> Range<usize> {
		self.range.clone()
	}
}

/// Iterator over the nodes in the document prolog.
///
/// Yields [`PrologNode`] values from the start of the document until the
/// first non-prolog token (the root element open-tag). A leading byte order
/// mark and whitespace are skipped. Malformed input causes the iterator to
/// stop rather than error; use [`XmlReader::root_element`](crate::XmlReader::root_element)
/// to check the document.
///
/// # Examples
/// ```
/// use roxml::prelude::*;
///
/// let xml = r#"<?xml version="1.0"?>
/// <!DOCTYPE note>
/// <!-- generated -->
/// <note/>"#;
///
/// for node in XmlReader::parse(xml).prolog() {
///     match node {
///         PrologNode::Declaration(decl) => assert_eq!(decl.version(), "1.0"),
///         PrologNode::Doctype(doctype) => assert_eq!(doctype.content(), "note"),
///         PrologNode::Comment(comment) => assert_eq!(comment.text(), " generated "),
///         PrologNode::PI(_) => unreachable!(),
///     }
/// }
/// ```
pub struct XmlProlog<'xml> {
	pub(crate) xml_text: &'xml str,
	pub(crate) pos: usize,
}

impl<'xml> Iterator for XmlProlog<'xml> {
	type Item = PrologNode<'xml>;

	fn next(&mut self) -> Option<Self::Item> {
		let b = self.xml_text.as_bytes();
		self.pos = skip_whitespace(self.xml_text, self.pos);
		if self.pos >= b.len() {
			return None;
		}
		if b[self.pos] != b'<' {
			return None; // non-'<' content not valid in prolog — stop
		}

		// Processing instruction or XML declaration
		if b.get(self.pos + 1) == Some(&b'?') {
			let end = find_bytes(b, self.pos + 2, b"?>")? + 2;
			let range = self.pos..end;
			self.pos = end;
			// the XML declaration is only allowed at the very start, other
			// uses of the reserved target `xml` make the document malformed
			if is_reserved_pi_at(b, range.start) {
				if range.start != bom_len(self.xml_text) || !is_declaration_at(b, range.start) {
					return None;
				}
				return Some(PrologNode::Declaration(XmlDeclaration {
					xml_text: self.xml_text,
					range,
				}));
			}
			return Some(PrologNode::PI(PrologPI {
				xml_text: self.xml_text,
				range,
			}));
		}

		// Comment
		if b.get(self.pos + 1..self.pos + 4) == Some(b"!--") {
			let end = find_bytes(b, self.pos + 4, b"-->")? + 3;
			let range = self.pos..end;
			self.pos = end;
			return Some(PrologNode::Comment(PrologComment {
				xml_text: self.xml_text,
				range,
			}));
		}

		// DOCTYPE, possibly with an internal subset
		if is_doctype_at(b, self.pos) {
			let end = find_doctype_end(b, self.pos)?;
			let range = self.pos..end;
			self.pos = end;
			return Some(PrologNode::Doctype(XmlDoctype {
				xml_text: self.xml_text,
				range,
			}));
		}

		// Anything else is the start of the root element — stop
		None
	}
}