xsd_parser/models/schema/
qname.rs

1use std::borrow::Cow;
2use std::fmt::{Debug, Formatter, Result as FmtResult};
3
4use quick_xml::name::{QName as QuickXmlQName, ResolveResult};
5use xsd_parser_types::misc::{format_utf8_slice, Namespace};
6
7use xsd_parser_types::quick_xml::{DeserializeBytes, DeserializeHelper, Error};
8
9/// Type that represents a a resolved [`QName`].
10///
11/// The namespace of this [`QName`] was resolved during deserialization.
12#[derive(Clone, Eq, PartialEq)]
13pub struct QName {
14    raw: Vec<u8>,
15    index: Option<usize>,
16    ns: Option<Namespace>,
17}
18
19impl QName {
20    /// Create a new [`QName`] instance from the passed `reader` and `raw` data.
21    #[must_use]
22    pub fn from_helper(helper: &mut DeserializeHelper, raw: &[u8]) -> Self {
23        let index = raw.iter().position(|x| *x == b':');
24        let ns = match helper.resolve(QuickXmlQName(raw), false).0 {
25            ResolveResult::Unbound | ResolveResult::Unknown(_) => None,
26            ResolveResult::Bound(ns) => Some(Namespace(Cow::Owned(ns.0.to_owned()))),
27        };
28        let raw = raw.to_owned();
29
30        Self { raw, index, ns }
31    }
32
33    /// Get the namespace of the [`QName`].
34    #[must_use]
35    pub fn namespace(&self) -> Option<&Namespace> {
36        self.ns.as_ref()
37    }
38
39    /// Get the prefix of the [`QName`].
40    #[must_use]
41    pub fn prefix(&self) -> Option<&[u8]> {
42        let index = self.index?;
43
44        Some(&self.raw[0..index])
45    }
46
47    /// Get the local name of the [`QName`].
48    #[must_use]
49    pub fn local_name(&self) -> &[u8] {
50        let index = self.index.map(|index| index + 1).unwrap_or_default();
51
52        &self.raw[index..]
53    }
54}
55
56impl DeserializeBytes for QName {
57    fn deserialize_bytes(helper: &mut DeserializeHelper, bytes: &[u8]) -> Result<Self, Error> {
58        Ok(Self::from_helper(helper, bytes))
59    }
60}
61
62#[allow(clippy::missing_fields_in_debug)]
63impl Debug for QName {
64    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
65        struct Helper<'a>(&'a [u8]);
66
67        impl Debug for Helper<'_> {
68            fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
69                write!(f, "b\"")?;
70                format_utf8_slice(self.0, f)?;
71                write!(f, "\"")?;
72
73                Ok(())
74            }
75        }
76
77        f.debug_struct("QName")
78            .field("raw", &Helper(&self.raw))
79            .field("ns", &self.ns)
80            .finish()
81    }
82}