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