Documentation
// Copyright © 2026 Stephan Kunz
//! Implementation of the `XmlReader`.

use crate::{
	epilog::XmlEpilog,
	error::Error,
	helpers::{find_bytes, parse_element_at, skip_whitespace},
	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`].
pub struct XmlReader<'xml> {
	xml_text: &'xml str,
}

impl<'xml> XmlReader<'xml> {
	/// Wraps `xml_doc` for lazy parsing. No work is done here.
	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.
	pub fn prolog(&self) -> XmlProlog<'xml> {
		XmlProlog {
			xml_text: self.xml_text,
			pos: 0,
		}
	}

	/// Returns the document's root element.
	///
	/// Processing instructions, comments, DOCTYPE, and the XML declaration
	/// that precede the root are skipped automatically.
	///
	/// # Errors
	/// - [`Error::NoRoot`] – source contains no element.
	/// - [`Error::MalformedXml`] – a PI, comment, DOCTYPE, or element tag is unclosed.
	pub fn root_element(&self) -> Result<XmlElement<'xml>, Error> {
		let b = self.xml_text.as_bytes();
		let len = b.len();
		let mut pos = 0;

		while pos < len {
			pos = skip_whitespace(self.xml_text, pos);
			if pos >= len {
				break;
			}
			if b[pos] != b'<' {
				pos += 1;
				continue;
			}
			if b.get(pos + 1) == Some(&b'?') {
				pos = find_bytes(b, pos + 2, b"?>").ok_or(Error::MalformedXml)? + 2;
				continue;
			}
			if b.get(pos + 1..pos + 4) == Some(b"!--") {
				pos = find_bytes(b, pos + 4, b"-->").ok_or(Error::MalformedXml)? + 3;
				continue;
			}
			if b.get(pos + 1..pos + 9) == Some(b"!DOCTYPE") || b.get(pos + 1..pos + 9) == Some(b"!doctype") {
				pos = b[pos..]
					.iter()
					.position(|&c| c == b'>')
					.ok_or(Error::MalformedXml)?
					+ pos + 1;
				continue;
			}
			return parse_element_at(self.xml_text, pos, len).ok_or(Error::MalformedXml);
		}
		Err(Error::NoRoot)
	}

	/// Returns an iterator over the document epilog (comments after the root
	/// element). Whitespace is silently skipped. Any other content stops the
	/// iterator. If no root element exists, the iterator is empty.
	pub fn epilog(&self) -> XmlEpilog<'xml> {
		let start = self
			.root_element()
			.map(|root| root.close.end)
			.unwrap_or(self.xml_text.len());
		XmlEpilog {
			xml_text: self.xml_text,
			pos: start,
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	const fn is_normal<T: Sized + Send + Sync>() {}

	#[test]
	const fn normal_types() {
		is_normal::<XmlReader>();
		is_normal::<&XmlReader>();
	}
}