Documentation
// Copyright © 2026 Stephan Kunz
//! Implementation of the [`XmlReader`](crate::xml_reader::XmlReader)s attribute type `XmlAttribute`.

use core::ops::Range;

/// A single `name="value"` pair inside an element's opening tag.
pub struct XmlAttribute<'xml> {
	xml_text: &'xml str,
	name: Range<usize>,
	value: Range<usize>,
}

impl<'xml> XmlAttribute<'xml> {
	/// Attribute name.
	pub fn name(&self) -> &'xml str {
		&self.xml_text[self.name.clone()]
	}

	/// Attribute value, without surrounding quotes.
	pub fn value(&self) -> &'xml str {
		&self.xml_text[self.value.clone()]
	}
}

// ── iterators ────────────────────────────────────────────────────────────────

/// Iterator over attributes in an element's opening tag.
pub struct XmlAttributes<'xml> {
	pub(crate) xml_text: &'xml str,
	pub(crate) pos: usize,
	pub(crate) end: usize,
}

impl<'xml> Iterator for XmlAttributes<'xml> {
	type Item = XmlAttribute<'xml>;

	fn next(&mut self) -> Option<Self::Item> {
		let b = self.xml_text.as_bytes();
		// Skip whitespace
		while self.pos < self.end && matches!(b[self.pos], b' ' | b'\t' | b'\n' | b'\r') {
			self.pos += 1;
		}
		if self.pos >= self.end || matches!(b[self.pos], b'/' | b'>') {
			return None;
		}
		// Name
		let name_start = self.pos;
		while self.pos < self.end && !matches!(b[self.pos], b'=' | b' ' | b'\t' | b'\n' | b'\r') {
			self.pos += 1;
		}
		let name_end = self.pos;
		// Advance to '='
		while self.pos < self.end && b[self.pos] != b'=' {
			self.pos += 1;
		}
		if self.pos >= self.end {
			return None;
		}
		self.pos += 1; // skip '='
		// Skip whitespace
		while self.pos < self.end && matches!(b[self.pos], b' ' | b'\t' | b'\n' | b'\r') {
			self.pos += 1;
		}
		if self.pos >= self.end {
			return None;
		}
		let quote = b[self.pos];
		if quote != b'"' && quote != b'\'' {
			return None;
		}
		self.pos += 1; // skip opening quote
		let val_start = self.pos;
		while self.pos < self.end && b[self.pos] != quote {
			self.pos += 1;
		}
		if self.pos >= self.end {
			return None;
		}
		let val_end = self.pos;
		self.pos += 1; // skip closing quote
		Some(XmlAttribute {
			xml_text: self.xml_text,
			name: name_start..name_end,
			value: val_start..val_end,
		})
	}
}

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

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

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

	// ── low-level helper branches that the public API cannot reach ──────────

	#[test]
	fn attributes_iter_returns_none_on_unterminated_quote() {
		// attr_end sits past the opening quote, but there is no closing quote
		// before it — the scan walks off the end.
		let xml = " attr=\"value";
		let mut iter = XmlAttributes {
			xml_text: xml,
			pos: 0,
			end: xml.len(),
		};
		assert!(iter.next().is_none());
	}
}