roxml 0.4.0

Read-only, zero-copy, lazy XML reader for no_std environments, without allocation
Documentation
// Copyright © 2026 Stephan Kunz
//! XML declaration node: `<?xml version="1.0" encoding="UTF-8"?>`.

use core::ops::Range;

use crate::xml_attribute::XmlAttributes;

/// The XML declaration that may appear at the very start of a document.
///
/// Pseudo-attributes (`version`, `encoding`, `standalone`) are parsed
/// on demand using the same zero-copy attribute iterator as element attributes.
#[derive(Clone)]
pub struct XmlDeclaration<'xml> {
	pub(crate) xml_text: &'xml str,
	/// Byte range of the full `<?xml … ?>` in the source.
	pub(crate) range: Range<usize>,
}

impl<'xml> XmlDeclaration<'xml> {
	/// Value of the `version` pseudo-attribute (e.g. `"1.0"`).
	/// Returns `""` if absent (malformed declaration).
	#[must_use]
	pub fn version(&self) -> &'xml str {
		self.pseudo_attr("version").unwrap_or("")
	}

	/// Value of the `encoding` pseudo-attribute, or `None` if absent.
	#[must_use]
	pub fn encoding(&self) -> Option<&'xml str> {
		self.pseudo_attr("encoding")
	}

	/// Value of the `standalone` pseudo-attribute, or `None` if absent.
	#[must_use]
	pub fn standalone(&self) -> Option<&'xml str> {
		self.pseudo_attr("standalone")
	}

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

	fn pseudo_attr(&self, name: &str) -> Option<&'xml str> {
		// Content between "<?xml" (5 bytes) and "?>" (2 bytes).
		let start = self.range.start + 5;
		let end = self.range.end.saturating_sub(2);
		XmlAttributes {
			xml_text: self.xml_text,
			pos: start,
			end,
		}
		.find(|a| a.name() == name)
		.map(|a| a.value())
	}
}