Documentation
// Copyright © 2026 Stephan Kunz
//! Body section node types: `BodyNode`, `BodyComment`.

use core::ops::Range;

use crate::{xml_element::XmlElement, xml_text::XmlText};

/// The set of node types that may appear as children of an XML element.
pub enum BodyNode<'xml> {
	/// A regular element: `<tag …>…</tag>` or `<tag/>`.
	Element(XmlElement<'xml>),
	/// Character data or a CDATA section.
	Text(XmlText<'xml>),
	/// An XML comment: `<!-- … -->`.
	Comment(BodyComment<'xml>),
}

/// A comment node inside an element body: `<!-- … -->`.
#[derive(Clone)]
pub struct BodyComment<'xml> {
	pub(crate) xml_text: &'xml str,
	/// Byte range of the full `<!-- … -->` in the source.
	pub(crate) range: Range<usize>,
	pub(crate) content_end: usize,
}

impl<'xml> BodyComment<'xml> {
	pub(crate) fn new(xml_text: &'xml str, range: Range<usize>, content_end: usize) -> Self {
		BodyComment {
			xml_text,
			range,
			content_end,
		}
	}

	/// Comment body with `<!--` and `-->` stripped.
	pub fn text(&self) -> &'xml str {
		let s = &self.xml_text[self.range.clone()];
		s.strip_prefix("<!--")
			.and_then(|r| r.strip_suffix("-->"))
			.unwrap_or(s)
	}

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

	/// Next sibling node within the parent element, or `None`.
	pub fn next_sibling(&self) -> Option<BodyNode<'xml>> {
		crate::helpers::next_body_sibling(self.xml_text, self.range.end, self.content_end)
	}
}

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

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

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

	#[test]
	fn comment_text_strips_markers() {
		let src = "<!-- hello world -->";
		let c = BodyComment::new(src, 0..src.len(), src.len());
		assert_eq!(c.text(), " hello world ");
		assert_eq!(c.range(), 0..src.len());
	}
}