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).
	pub fn version(&self) -> &'xml str {
		self.pseudo_attr("version").unwrap_or("")
	}

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

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

	/// Byte range of this node in the source text.
	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())
	}
}

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

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

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

	#[test]
	fn version_only() {
		let src = r#"<?xml version="1.0"?>"#;
		let d = XmlDeclaration {
			xml_text: src,
			range: 0..src.len(),
		};
		assert_eq!(d.version(), "1.0");
		assert_eq!(d.encoding(), None);
		assert_eq!(d.standalone(), None);
	}

	#[test]
	fn version_and_encoding() {
		let src = r#"<?xml version="1.0" encoding="UTF-8"?>"#;
		let d = XmlDeclaration {
			xml_text: src,
			range: 0..src.len(),
		};
		assert_eq!(d.version(), "1.0");
		assert_eq!(d.encoding(), Some("UTF-8"));
		assert_eq!(d.standalone(), None);
	}

	#[test]
	fn all_three_pseudo_attributes() {
		let src = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#;
		let d = XmlDeclaration {
			xml_text: src,
			range: 0..src.len(),
		};
		assert_eq!(d.version(), "1.0");
		assert_eq!(d.encoding(), Some("UTF-8"));
		assert_eq!(d.standalone(), Some("yes"));
	}

	#[test]
	fn range_covers_full_declaration() {
		let src = r#"<?xml version="1.0"?>"#;
		let d = XmlDeclaration {
			xml_text: src,
			range: 0..src.len(),
		};
		assert_eq!(&src[d.range()], src);
	}
}