Documentation
// Copyright © 2026 Stephan Kunz
//! Body text node — covers both plain character data and CDATA sections.

use core::ops::Range;

/// A text node in the body of an element.
///
/// Covers both plain character data and `<![CDATA[…]]>` sections; `text()`
/// always returns the logical text content without CDATA markers.
#[derive(Clone)]
pub struct XmlText<'xml> {
	pub(crate) xml_text: &'xml str,
	/// Byte range of the raw source (including `<![CDATA[` / `]]>` if present).
	pub(crate) range: Range<usize>,
	/// Upper bound for sibling navigation (parent's close-tag start).
	pub(crate) content_end: usize,
}

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

	/// Text content. For CDATA sections the `<![CDATA[` / `]]>` markers are
	/// stripped; for plain text the slice is returned as-is.
	pub fn text(&self) -> &'xml str {
		let s = &self.xml_text[self.range.clone()];
		s.strip_prefix("<![CDATA[")
			.and_then(|r| r.strip_suffix("]]>"))
			.unwrap_or(s)
	}

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

	/// Next sibling node within the parent element, or `None`.
	pub fn next_sibling(&self) -> Option<crate::body::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::<XmlText>();
		is_normal::<&XmlText>();
	}

	#[test]
	fn plain_text_returns_slice() {
		let t = XmlText::new("hello world", 0..11, 11);
		assert_eq!(t.text(), "hello world");
		assert_eq!(t.range(), 0..11);
	}

	#[test]
	fn cdata_strips_markers() {
		let src = "<![CDATA[raw content]]>";
		let t = XmlText::new(src, 0..src.len(), src.len());
		assert_eq!(t.text(), "raw content");
	}
}