use crate::{NamespaceDeclaration, NamespaceUri, NcName, QName};
#[derive(Clone, Copy)]
pub struct QNameCollectionIndex {
global_index: u32,
local_index: u32,
}
impl PartialEq for QNameCollectionIndex {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.global_index == other.global_index
}
}
impl Eq for QNameCollectionIndex {}
impl PartialEq<QName> for QNameCollectionIndex {
#[inline]
fn eq(&self, _other: &QName) -> bool {
false
}
}
impl PartialEq<QNameCollectionIndex> for QName {
#[inline]
fn eq(&self, _other: &QNameCollectionIndex) -> bool {
false
}
}
pub struct QNameCollection {
qnames: Vec<QName>,
}
impl Default for QNameCollection {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl QNameCollection {
#[must_use]
#[inline]
pub fn new() -> Self {
Self { qnames: Vec::new() }
}
fn find(
&self,
namespace: &NamespaceDeclaration,
local_name: &NcName,
) -> Option<QNameCollectionIndex> {
if let Some((local_index, _qname)) = self.qnames.iter().enumerate().find(|(_, qname)| {
qname.local_name() == *local_name
&& qname
.namespace_uri()
.as_ref()
.map_or("".to_string(), |ns| ns.to_string())
== namespace.namespace_uri.to_string()
}) {
return Some(QNameCollectionIndex {
global_index: 0, local_index: u32::try_from(local_index).unwrap_or_else(|_| unreachable!()),
});
}
None
}
#[inline]
pub fn add(
&mut self,
namespace: NamespaceDeclaration,
local_name: NcName,
) -> QNameCollectionIndex {
if let Some(index) = self.find(&namespace, &local_name) {
return index;
}
let qname = QName::new(local_name, Some(namespace));
let index = QNameCollectionIndex {
global_index: 0, local_index: u32::try_from(self.qnames.len())
.expect("Too many QNames in the QNameCollection"),
};
self.qnames.push(qname);
index
}
#[must_use]
#[inline]
pub fn get(&self, index: QNameCollectionIndex) -> &QName {
&self.qnames[index.local_index as usize]
}
#[must_use]
#[inline]
pub fn local_name(&self, index: QNameCollectionIndex) -> NcName {
self.get(index).local_name()
}
#[must_use]
#[inline]
pub fn namespace_uri(&self, index: QNameCollectionIndex) -> Option<NamespaceUri> {
self.get(index).namespace_uri()
}
}