qualname 0.0.2

Support for XML Namespaces Qualified Name
Documentation
use std::{collections::HashMap, fmt::Display, rc::Rc, sync::LazyLock};

use crate::{NamespacePrefix, NamespaceUri};

// Internal definitions, used to test for invalidity
static XMLNSURI: LazyLock<NamespaceUri> =
    LazyLock::new(|| NamespaceUri::try_from("http://www.w3.org/2000/xmlns/").unwrap());
static XMLNSPREFIX: LazyLock<Option<NamespacePrefix>> =
    LazyLock::new(|| Some(NamespacePrefix(String::from("xmlns"))));

/// An invalid namespace declaration
#[derive(Debug)]
pub struct InvalidNamespaceDeclaration;
impl Display for InvalidNamespaceDeclaration {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Invalid namespace declaration")
    }
}
impl std::error::Error for InvalidNamespaceDeclaration {}

/// A namespace declaration, consisting of an optional [NamespacePrefix] (None for default namespace) and a [NamespaceUri]
#[derive(Clone, Debug)]
pub struct NamespaceDeclaration {
    pub(crate) namespace_prefix: Option<NamespacePrefix>,
    pub(crate) namespace_uri: NamespaceUri,
}
impl NamespaceDeclaration {
    /**
     * # Errors
     * If the namespace is empty and the prefix is not, an error is returned.
     * Also, if the "xmlns" or "xml" prefixes are associated with different
     * namespaces from the predefined ones, an error is returned.
     */
    #[inline]
    pub fn new(
        namespace_prefix: Option<NamespacePrefix>,
        namespace_uri: NamespaceUri,
    ) -> Result<Self, InvalidNamespaceDeclaration> {
        if (namespace_prefix == XML.namespace_prefix && namespace_uri != XML.namespace_uri)
            || (namespace_prefix != XML.namespace_prefix && namespace_uri == XML.namespace_uri)
        {
            return Err(InvalidNamespaceDeclaration);
        }
        if (namespace_prefix == *XMLNSPREFIX && namespace_uri != *XMLNSURI)
            || (namespace_prefix != *XMLNSPREFIX && namespace_uri == *XMLNSURI)
        {
            return Err(InvalidNamespaceDeclaration);
        }
        Ok(Self {
            namespace_prefix,
            namespace_uri,
        })
    }
}

static XML: LazyLock<NamespaceDeclaration> = LazyLock::new(|| NamespaceDeclaration {
    namespace_prefix: Some(NamespacePrefix::try_from("xml").unwrap()),
    namespace_uri: NamespaceUri::try_from("http://www.w3.org/XML/1998/namespace").unwrap(),
});

/// A NamespaceMap is a way of looking up a [NamespaceDeclaration] given either a prefix or a Namespace URI.
/// For use in keeping track of in-scope namespaces.
#[derive(Clone, Debug)]
pub struct NamespaceMap {
    prefixes: HashMap<Option<NamespacePrefix>, Rc<NamespaceDeclaration>>,
    uris: HashMap<NamespaceUri, Rc<NamespaceDeclaration>>,
}

impl NamespaceMap {
    pub fn new() -> Self {
        let mut nm = Self {
            prefixes: HashMap::new(),
            uris: HashMap::new(),
        };
        // Initialise with known namespaces
        nm.push(
            NamespaceDeclaration::new(
                Some(NamespacePrefix::try_from("xml").unwrap()),
                NamespaceUri::try_from("http://www.w3.org/XML/1998/namespace").unwrap(),
            )
            .unwrap(),
        );
        nm
    }
    pub fn push(&mut self, nsd: NamespaceDeclaration) {
        let nsdr = Rc::new(nsd.clone());
        self.prefixes
            .insert(nsd.namespace_prefix.clone(), nsdr.clone());
        self.uris.insert(nsd.namespace_uri.clone(), nsdr);
    }
    pub fn namespace_uri(&self, prefix: &Option<NamespacePrefix>) -> Option<NamespaceUri> {
        self.prefixes.get(prefix).map(|nd| nd.namespace_uri.clone())
    }
    pub fn prefix(&self, ns_uri: &NamespaceUri) -> Option<NamespacePrefix> {
        self.uris
            .get(ns_uri)
            .map_or(None, |nd| nd.namespace_prefix.clone())
    }
    /// Remove a namespace from the map, referenced by its prefix.
    /// If successful, returns the now-removed namespace declaration.
    /// Otherwise returns None.
    pub fn pop_prefix(&mut self, prefix: &Option<NamespacePrefix>) -> Option<NamespaceDeclaration> {
        if let Some(nsd) = self.prefixes.remove(&prefix) {
            self.uris.remove(&nsd.namespace_uri);
            Some((*nsd).clone())
        } else {
            None
        }
    }
    // TODO: pop_uri()
}