use std::borrow::Cow;
use simdhtml::document::Document;
use simdhtml::document::id::{NO_ATTR, NodeId, TagId};
use crate::access::{attr_name, attr_value};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum RefKind {
Document,
Element,
Text,
Attribute,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NodeRef {
kind: RefKind,
id: NodeId,
attr: u32,
}
impl NodeRef {
pub(crate) fn new(kind: RefKind, id: NodeId, attr: u32) -> Self {
Self { kind, id, attr }
}
pub fn document() -> Self {
Self::new(RefKind::Document, NodeId::new(0), NO_ATTR)
}
pub fn element(id: NodeId) -> Self {
Self::new(RefKind::Element, id, NO_ATTR)
}
pub fn text(id: NodeId) -> Self {
Self::new(RefKind::Text, id, NO_ATTR)
}
pub fn attribute(id: NodeId, attr: u32) -> Self {
Self::new(RefKind::Attribute, id, attr)
}
pub fn kind(self) -> RefKind {
self.kind
}
pub fn node_id(self) -> NodeId {
self.id
}
pub fn attr_index(self) -> Option<u32> {
(self.kind == RefKind::Attribute).then_some(self.attr)
}
pub(crate) fn order_key(self) -> (NodeId, u32) {
match self.kind {
RefKind::Attribute => (self.id, self.attr + 1),
_ => (self.id, 0),
}
}
pub fn string_value<'a>(self, doc: &'a Document<'_>) -> Cow<'a, str> {
match self.kind {
RefKind::Attribute => attr_value(doc, self.attr),
RefKind::Text => match crate::xpath::eval::text_run(doc, self.id) {
None => doc.text(self.id),
Some(last) => {
let mut out = String::new();
for id in self.id.get()..=last.get() {
out.push_str(&doc.text(NodeId::new(id)));
}
Cow::Owned(out)
}
},
RefKind::Element => Cow::Owned(crate::access::text_content(doc, self.id)),
RefKind::Document => {
let root = doc.node(self.id).first_child();
if root == NodeId::NONE {
Cow::Borrowed("")
} else {
Cow::Owned(crate::access::text_content(doc, root))
}
}
}
}
pub fn name<'a>(self, doc: &'a Document<'_>) -> &'a str {
match self.kind {
RefKind::Element => {
let tag = doc.node(self.id).tag_token();
if tag == TagId::NONE {
""
} else {
doc.tag_name(tag)
}
}
RefKind::Attribute => std::str::from_utf8(attr_name(doc, self.attr))
.expect("Document input is valid UTF-8"),
_ => "",
}
}
}
#[derive(Clone, Debug)]
pub enum Value {
Nodes(Vec<NodeRef>),
Str(String),
Number(f64),
Bool(bool),
}
impl Value {
pub(crate) fn to_boolean(&self) -> bool {
match self {
Self::Nodes(nodes) => !nodes.is_empty(),
Self::Str(s) => !s.is_empty(),
Self::Number(n) => *n != 0.0 && !n.is_nan(),
Self::Bool(b) => *b,
}
}
pub(crate) fn to_number(&self, doc: &Document<'_>) -> f64 {
match self {
Self::Number(n) => *n,
Self::Bool(b) => f64::from(u8::from(*b)),
Self::Str(s) => parse_number(s),
Self::Nodes(nodes) => match nodes.first() {
Some(node) => parse_number(&node.string_value(doc)),
None => f64::NAN,
},
}
}
pub(crate) fn to_string(&self, doc: &Document<'_>) -> String {
match self {
Self::Str(s) => s.clone(),
Self::Bool(true) => "true".to_owned(),
Self::Bool(false) => "false".to_owned(),
Self::Number(n) => format_number(*n),
Self::Nodes(nodes) => match nodes.first() {
Some(node) => node.string_value(doc).into_owned(),
None => String::new(),
},
}
}
}
pub(crate) fn parse_number(text: &str) -> f64 {
let trimmed = text.trim_matches(|c: char| c == ' ' || c == '\t' || c == '\n' || c == '\r');
if trimmed.is_empty() {
return f64::NAN;
}
let mut seen_dot = false;
let mut seen_digit = false;
for (i, byte) in trimmed.bytes().enumerate() {
match byte {
b'0'..=b'9' => seen_digit = true,
b'.' if !seen_dot => seen_dot = true,
b'-' | b'+' if i == 0 => {}
_ => return f64::NAN,
}
}
if seen_digit {
trimmed.parse().unwrap_or(f64::NAN)
} else {
f64::NAN
}
}
fn format_number(value: f64) -> String {
if value.is_nan() {
"NaN".to_owned()
} else if value.is_infinite() {
if value > 0.0 { "Infinity" } else { "-Infinity" }.to_owned()
} else if value == value.trunc() && value.abs() < 1e15 {
format!("{}", value as i64)
} else {
format!("{value}")
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Nodes(nodes) => write!(f, "<{} nodes>", nodes.len()),
Self::Str(s) => write!(f, "{s}"),
Self::Number(n) => write!(f, "{}", format_number(*n)),
Self::Bool(b) => write!(f, "{b}"),
}
}
}