use crate::alloc_prelude::*;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap as HashMap;
#[cfg(feature = "std")]
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Namespace {
pub prefix: Option<Box<str>>,
pub uri: Box<str>,
}
impl Namespace {
pub fn new(prefix: Option<impl Into<Box<str>>>, uri: impl Into<Box<str>>) -> Self {
Self {
prefix: prefix.map(Into::into),
uri: uri.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QName {
pub prefix: Option<Box<str>>,
pub local_name: Box<str>,
pub namespace_uri: Option<Box<str>>,
}
impl QName {
pub fn new(
prefix: Option<impl Into<Box<str>>>,
local_name: impl Into<Box<str>>,
namespace_uri: Option<impl Into<Box<str>>>,
) -> Self {
Self {
prefix: prefix.map(Into::into),
local_name: local_name.into(),
namespace_uri: namespace_uri.map(Into::into),
}
}
pub fn split_prefix(raw: &str) -> (Option<&str>, &str) {
if let Some((prefix, local)) = raw.split_once(':') {
(Some(prefix), local)
} else {
(None, raw)
}
}
}
#[derive(Debug, Clone)]
pub struct NamespaceScope {
scopes: Vec<HashMap<String, String>>,
}
impl Default for NamespaceScope {
fn default() -> Self {
let mut initial = HashMap::new();
initial.insert(
"xml".to_string(),
"http://www.w3.org/XML/1998/namespace".to_string(),
);
initial.insert(
"xmlns".to_string(),
"http://www.w3.org/2000/xmlns/".to_string(),
);
Self {
scopes: vec![initial],
}
}
}
impl NamespaceScope {
pub fn new() -> Self {
Self::default()
}
pub fn push_scope(&mut self) {
self.scopes.push(HashMap::new());
}
pub fn pop_scope(&mut self) {
if self.scopes.len() > 1 {
self.scopes.pop();
}
}
pub fn declare(&mut self, prefix: Option<&str>, uri: &str) {
if let Some(current) = self.scopes.last_mut() {
let key = prefix.unwrap_or("").to_string();
current.insert(key, uri.to_string());
}
}
pub fn resolve_prefix(&self, prefix: Option<&str>) -> Option<&str> {
let key = prefix.unwrap_or("");
for scope in self.scopes.iter().rev() {
if let Some(uri) = scope.get(key) {
if uri.is_empty() {
return None;
}
return Some(uri.as_str());
}
}
None
}
pub fn resolve_qname(&self, raw_name: &str, is_attribute: bool) -> QName {
let (prefix, local) = QName::split_prefix(raw_name);
let uri: Option<Box<str>> = if is_attribute && prefix.is_none() {
None
} else {
self.resolve_prefix(prefix).map(Into::into)
};
QName::new(prefix, local, uri)
}
}