use crate::{
names::{InvalidQName, NamespaceUri, NcName},
namespace_declaration::NamespaceDeclaration,
unique_qname::UniqueQName,
};
use std::{
cmp::Ordering,
fmt::Display,
hash::{Hash, Hasher},
};
#[derive(Clone, Debug)]
pub struct QName {
qname: UniqueQName,
}
impl QName {
#[must_use]
#[inline]
pub fn new(local_name: NcName, namespace: Option<NamespaceDeclaration>) -> Self {
Self {
qname: UniqueQName::new(namespace.map(|nd| nd.namespace_uri), local_name),
}
}
#[must_use]
#[inline]
pub fn new_from_parts(local_name: NcName, namespace_uri: Option<NamespaceUri>) -> Self {
Self {
qname: UniqueQName::new(namespace_uri, local_name),
}
}
#[must_use]
#[inline]
pub fn from_local_name(local_name: NcName) -> Self {
Self {
qname: UniqueQName::new(None, local_name),
}
}
#[must_use]
#[inline]
pub fn local_name(&self) -> NcName {
self.qname.local_name()
}
#[must_use]
#[inline]
pub fn namespace_uri(&self) -> Option<NamespaceUri> {
self.qname.namespace_uri()
}
}
impl TryFrom<&str> for QName {
type Error = InvalidQName;
#[inline]
fn try_from(value: &str) -> Result<Self, Self::Error> {
Ok(QName {
qname: UniqueQName::new(None, NcName::try_from(value)?),
})
}
}
impl PartialEq for QName {
#[inline]
fn eq(&self, other: &Self) -> bool {
PartialEq::eq(&self.qname, &other.qname)
}
}
impl Eq for QName {}
impl PartialOrd for QName {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.local_name().partial_cmp(&other.local_name()).map(|p| {
if p == Ordering::Equal {
match (self.namespace_uri(), other.namespace_uri()) {
(None, None) => Ordering::Equal,
(Some(sns), Some(ons)) => sns
.to_string()
.partial_cmp(&ons.to_string())
.map_or(Ordering::Equal, |q| q),
_ => Ordering::Less,
}
} else {
p
}
})
}
}
impl Ord for QName {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).map_or(Ordering::Equal, |p| p)
}
}
impl Hash for QName {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.qname.hash(state);
}
}
impl Display for QName {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let nsuri = self
.namespace_uri()
.map_or(String::from(""), |ns| format!("{{{}}}", ns.to_string()));
write!(f, "{}{}", nsuri, self.local_name().to_string())
}
}