Skip to main content

xtce_model/
xml.rs

1//! A compact, arena-backed XML tree tuned for XTCE.
2//!
3//! # Why a tree and not a pure SAX pass
4//!
5//! XTCE is not a stream: `<BaseContainer>` points backwards or forwards, `<ParameterRefEntry>`
6//! names types defined earlier or later, and several elements are only meaningful together
7//! with siblings. A single streaming pass would need a hand-rolled state machine with a
8//! deferred-fixup table for every one of those cases. Building a tree first keeps the
9//! semantic pass declarative (`node.child(Tag::EntryList)`) at the cost of one compact
10//! arena.
11//!
12//! # Why it is still fast
13//!
14//! Nothing here allocates per element. Element names, attribute names, attribute values and
15//! text are appended to one shared `String` arena and addressed by `(start, len)`, so the
16//! tree is three flat `Vec`s of `Copy` records with no `String`, no `Rc`, and no per-node
17//! allocation.
18//!
19//! The arena deliberately does *not* deduplicate. An earlier version interned every
20//! attribute value, which sounds attractive — `encoding="unsigned"` appears 205 times in one
21//! test file — but interning costs a hash lookup per value where the arena costs a memcpy of
22//! about eight bytes, and the 1.6 MB test file has roughly a quarter of a million of them.
23//! Deduplication belongs in the IR, which keeps only the names it actually needs; the tree is
24//! transient and is dropped as soon as lowering finishes.
25//!
26//! Tag and attribute-key recognition is a `match` on the local name rather than a hash
27//! lookup: the vocabulary is a small closed set of short strings, which `rustc` compiles into
28//! a length switch and a handful of comparisons.
29
30use quick_xml::Reader;
31use quick_xml::events::Event;
32
33use crate::error::{ParseError, ParseErrorKind};
34use crate::ids::Span;
35
36/// Sentinel for "no node"; the arena can never hold `u32::MAX` nodes.
37const NONE: u32 = u32::MAX;
38
39macro_rules! symbols {
40    ($(#[$meta:meta])* $vis:vis enum $name:ident { $($variant:ident => $text:literal),* $(,)? }) => {
41        $(#[$meta])*
42        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
43        $vis enum $name {
44            $(
45                #[doc = concat!("The XML symbol `", $text, "`.")]
46                $variant,
47            )*
48            /// Any symbol outside the vocabulary this crate understands.
49            Other,
50        }
51
52        impl $name {
53            /// Every named variant, in declaration order.
54            $vis const ALL: &'static [$name] = &[$($name::$variant,)*];
55
56            /// The XML spelling of this symbol; `""` for [`Self::Other`].
57            #[must_use]
58            $vis const fn text(self) -> &'static str {
59                match self {
60                    $($name::$variant => $text,)*
61                    $name::Other => "",
62                }
63            }
64
65            /// Recognises a local name, returning [`Self::Other`] for anything outside the
66            /// vocabulary.
67            #[must_use]
68            $vis fn from_text(text: &str) -> Self {
69                match text {
70                    $($text => $name::$variant,)*
71                    _ => $name::Other,
72                }
73            }
74        }
75    };
76}
77
78symbols! {
79    /// XTCE element local names that carry meaning for telemetry decoding.
80    ///
81    /// Namespace prefixes are stripped before lookup, so `<xtce:SpaceSystem>`,
82    /// `<SpaceSystem>` and a default-namespaced `<SpaceSystem>` all map to
83    /// [`Tag::SpaceSystem`]. All three spellings occur in the wild — the reference
84    /// implementation ships a test file for each.
85    pub enum Tag {
86        SpaceSystem => "SpaceSystem",
87        TelemetryMetaData => "TelemetryMetaData",
88        CommandMetaData => "CommandMetaData",
89        ArgumentTypeSet => "ArgumentTypeSet",
90        MetaCommandSet => "MetaCommandSet",
91        MetaCommand => "MetaCommand",
92        BaseMetaCommand => "BaseMetaCommand",
93        ArgumentAssignmentList => "ArgumentAssignmentList",
94        ArgumentAssignment => "ArgumentAssignment",
95        ArgumentList => "ArgumentList",
96        Argument => "Argument",
97        CommandContainer => "CommandContainer",
98        CommandContainerSet => "CommandContainerSet",
99        ArgumentRefEntry => "ArgumentRefEntry",
100        ArrayArgumentRefEntry => "ArrayArgumentRefEntry",
101        FixedValueEntry => "FixedValueEntry",
102        IntegerArgumentType => "IntegerArgumentType",
103        FloatArgumentType => "FloatArgumentType",
104        StringArgumentType => "StringArgumentType",
105        BinaryArgumentType => "BinaryArgumentType",
106        BooleanArgumentType => "BooleanArgumentType",
107        EnumeratedArgumentType => "EnumeratedArgumentType",
108        AbsoluteTimeArgumentType => "AbsoluteTimeArgumentType",
109        RelativeTimeArgumentType => "RelativeTimeArgumentType",
110        ArrayArgumentType => "ArrayArgumentType",
111        AggregateArgumentType => "AggregateArgumentType",
112        ParameterTypeSet => "ParameterTypeSet",
113        ParameterSet => "ParameterSet",
114        ContainerSet => "ContainerSet",
115        Parameter => "Parameter",
116        SequenceContainer => "SequenceContainer",
117        BaseContainer => "BaseContainer",
118        RestrictionCriteria => "RestrictionCriteria",
119        EntryList => "EntryList",
120        ParameterRefEntry => "ParameterRefEntry",
121        ContainerRefEntry => "ContainerRefEntry",
122        IndirectParameterRefEntry => "IndirectParameterRefEntry",
123        ArrayParameterRefEntry => "ArrayParameterRefEntry",
124        LocationInContainerInBits => "LocationInContainerInBits",
125        IntegerParameterType => "IntegerParameterType",
126        FloatParameterType => "FloatParameterType",
127        StringParameterType => "StringParameterType",
128        BinaryParameterType => "BinaryParameterType",
129        BooleanParameterType => "BooleanParameterType",
130        EnumeratedParameterType => "EnumeratedParameterType",
131        AbsoluteTimeParameterType => "AbsoluteTimeParameterType",
132        RelativeTimeParameterType => "RelativeTimeParameterType",
133        ArrayParameterType => "ArrayParameterType",
134        DimensionList => "DimensionList",
135        Dimension => "Dimension",
136        StartingIndex => "StartingIndex",
137        EndingIndex => "EndingIndex",
138        AggregateParameterType => "AggregateParameterType",
139        MemberList => "MemberList",
140        Member => "Member",
141        IntegerDataEncoding => "IntegerDataEncoding",
142        FloatDataEncoding => "FloatDataEncoding",
143        StringDataEncoding => "StringDataEncoding",
144        BinaryDataEncoding => "BinaryDataEncoding",
145        Encoding => "Encoding",
146        SizeInBits => "SizeInBits",
147        Fixed => "Fixed",
148        FixedValue => "FixedValue",
149        Variable => "Variable",
150        DynamicValue => "DynamicValue",
151        DiscreteLookupList => "DiscreteLookupList",
152        DiscreteLookup => "DiscreteLookup",
153        LeadingSize => "LeadingSize",
154        TerminationChar => "TerminationChar",
155        ParameterInstanceRef => "ParameterInstanceRef",
156        LinearAdjustment => "LinearAdjustment",
157        EnumerationList => "EnumerationList",
158        Enumeration => "Enumeration",
159        Comparison => "Comparison",
160        ComparisonList => "ComparisonList",
161        BooleanExpression => "BooleanExpression",
162        Condition => "Condition",
163        ANDedConditions => "ANDedConditions",
164        ORedConditions => "ORedConditions",
165        ComparisonOperator => "ComparisonOperator",
166        Value => "Value",
167        DefaultCalibrator => "DefaultCalibrator",
168        ContextCalibratorList => "ContextCalibratorList",
169        ContextCalibrator => "ContextCalibrator",
170        ContextMatch => "ContextMatch",
171        Calibrator => "Calibrator",
172        PolynomialCalibrator => "PolynomialCalibrator",
173        SplineCalibrator => "SplineCalibrator",
174        MathOperationCalibrator => "MathOperationCalibrator",
175        Term => "Term",
176        SplinePoint => "SplinePoint",
177        CustomAlgorithm => "CustomAlgorithm",
178        UnitSet => "UnitSet",
179        Unit => "Unit",
180        LongDescription => "LongDescription",
181        ReferenceTime => "ReferenceTime",
182        Epoch => "Epoch",
183        OffsetFrom => "OffsetFrom",
184        RepeatEntry => "RepeatEntry",
185        Count => "Count",
186        IncludeCondition => "IncludeCondition",
187        ServiceSet => "ServiceSet",
188        MessageSet => "MessageSet",
189        StreamSet => "StreamSet",
190        AlgorithmSet => "AlgorithmSet",
191        AliasSet => "AliasSet",
192        AncillaryDataSet => "AncillaryDataSet",
193    }
194}
195
196impl Tag {
197    /// Whether this element opens a section telemetry decoding never reads.
198    ///
199    /// Checked as an enum comparison rather than by scanning a list of strings: this runs
200    /// once per element, and the largest test file has twenty thousand of them.
201    #[must_use]
202    const fn is_skipped_section(self) -> bool {
203        matches!(
204            self,
205            Self::ServiceSet
206                | Self::MessageSet
207                | Self::StreamSet
208                | Self::AlgorithmSet
209                | Self::AliasSet
210                | Self::AncillaryDataSet
211        )
212    }
213}
214
215symbols! {
216    /// XTCE attribute names that carry meaning for telemetry decoding.
217    pub enum AttrKey {
218        Name => "name",
219        Abstract => "abstract",
220        ShortDescription => "shortDescription",
221        ParameterRef => "parameterRef",
222        ContainerRef => "containerRef",
223        ParameterTypeRef => "parameterTypeRef",
224        ArgumentTypeRef => "argumentTypeRef",
225        ArgumentRef => "argumentRef",
226        ArgumentName => "argumentName",
227        ArgumentValue => "argumentValue",
228        MetaCommandRef => "metaCommandRef",
229        BinaryValue => "binaryValue",
230        ArrayTypeRef => "arrayTypeRef",
231        TypeRef => "typeRef",
232        SizeInBits => "sizeInBits",
233        Encoding => "encoding",
234        ByteOrder => "byteOrder",
235        Value => "value",
236        Label => "label",
237        MaxValue => "maxValue",
238        ComparisonOperator => "comparisonOperator",
239        UseCalibratedValue => "useCalibratedValue",
240        Slope => "slope",
241        Intercept => "intercept",
242        Order => "order",
243        Extrapolate => "extrapolate",
244        Raw => "raw",
245        Calibrated => "calibrated",
246        Coefficient => "coefficient",
247        Exponent => "exponent",
248        Offset => "offset",
249        Scale => "scale",
250        Units => "units",
251        SizeInBitsOfSizeTag => "sizeInBitsOfSizeTag",
252        InitialValue => "initialValue",
253        ReferenceLocation => "referenceLocation",
254        ZeroStringValue => "zeroStringValue",
255        OneStringValue => "oneStringValue",
256    }
257}
258
259// Sections of an XTCE document that nothing here reads are dropped during parsing rather
260// than materialised and ignored — see `Tag::is_skipped_section`. Skipped sections are
261// recorded so `xtce info` can report what the file contained but this crate did not model.
262//
263// `CommandMetaData` used to be on that list, and dropping it was the larger saving: in a
264// real mission database the command half can be bigger than the telemetry half. It is kept
265// now because a spacecraft has to read what the ground sends it, and a telecommand is
266// defined there and nowhere else.
267
268/// One element in the arena.
269#[derive(Clone, Copy, Debug)]
270pub struct Node {
271    tag: Tag,
272    name: Span,
273    parent: u32,
274    first_child: u32,
275    next_sibling: u32,
276    attr_start: u32,
277    attr_len: u32,
278    /// Text content, present only for elements with no element children.
279    text: Span,
280    has_text: bool,
281}
282
283#[derive(Clone, Copy, Debug)]
284struct Attr {
285    key: AttrKey,
286    name: Span,
287    value: Span,
288}
289
290/// A parsed XTCE document: a flat arena of elements plus the interner backing every name.
291pub struct Dom {
292    nodes: Vec<Node>,
293    attrs: Vec<Attr>,
294    /// `last_child[i]` is the most recently appended child of node `i`, or [`NONE`].
295    /// Keeping it out of [`Node`] costs one extra `Vec` during construction but makes
296    /// appending O(1) for wide parents such as `ParameterSet`, which holds thousands of
297    /// children in the larger test files.
298    last_child: Vec<u32>,
299    /// Every name, attribute value and text run, concatenated.
300    arena: String,
301    skipped_sections: Vec<String>,
302    xmlns: Option<String>,
303}
304
305/// A borrowed handle to one element, carrying the arena it came from.
306///
307/// This is the type the semantic pass works with. It is `Copy` and two words wide, so
308/// navigation (`child`, `children`, `attr`) is free of allocation and of lifetime noise.
309#[derive(Clone, Copy)]
310pub struct Element<'d> {
311    dom: &'d Dom,
312    index: u32,
313}
314
315impl Dom {
316    /// Parses an XTCE document from a UTF-8 string.
317    ///
318    /// # Errors
319    ///
320    /// Returns [`ParseError`] if the input is not well-formed XML or contains no root
321    /// element.
322    pub fn parse(input: &str) -> Result<Self, ParseError> {
323        // Sized from the largest file in `testdata` (1.6 MB, ~46 k elements, ~100 k
324        // attributes) so that a typical document never reallocates mid-parse. The arena
325        // holds names and values only, which is a fraction of the source.
326        let approx_elements = input.len() / 48;
327        let mut dom = Self {
328            nodes: Vec::with_capacity(approx_elements),
329            attrs: Vec::with_capacity(approx_elements * 2),
330            last_child: Vec::with_capacity(approx_elements),
331            // Only unrecognised names and attribute values reach the arena, which on real
332            // XTCE is a small fraction of the source; a quarter of the input length has
333            // never needed to grow on the bundled files.
334            arena: String::with_capacity(input.len() / 4),
335            skipped_sections: Vec::new(),
336            xmlns: None,
337        };
338        dom.run(input)?;
339        Ok(dom)
340    }
341
342    /// Appends `text` to the arena and returns its span.
343    #[inline]
344    fn push_text(&mut self, text: &str) -> Span {
345        let start = self.arena.len();
346        self.arena.push_str(text);
347        Span::between(start, self.arena.len())
348    }
349
350    #[inline]
351    fn str_at(&self, span: Span) -> &str {
352        let start = span.start();
353        self.arena
354            .get(start..start + span.len())
355            .unwrap_or_default()
356    }
357
358    fn run(&mut self, input: &str) -> Result<(), ParseError> {
359        let mut reader = Reader::from_str(input);
360        let config = reader.config_mut();
361        config.trim_text(true);
362        config.expand_empty_elements = false;
363        config.check_end_names = true;
364
365        // Ancestors of the element currently being filled; `open.last()` is its index.
366        let mut open: Vec<u32> = Vec::with_capacity(32);
367        // Depth of the skipped subtree we are inside, if any.
368        let mut skipping: Option<usize> = None;
369        // Character data seen since the last tag. quick-xml splits a text run at every
370        // entity reference (`&amp;` arrives as its own event), so text must be accumulated
371        // rather than taken from a single event.
372        let mut scratch = String::new();
373
374        loop {
375            let event = match reader.read_event() {
376                Ok(event) => event,
377                Err(source) => return Err(ParseError::at_offset(reader.buffer_position(), source)),
378            };
379
380            match event {
381                Event::Start(start) => {
382                    if let Some(depth) = skipping.as_mut() {
383                        *depth += 1;
384                        continue;
385                    }
386                    match self.open_element(&start, open.last().copied())? {
387                        Some(index) => open.push(index),
388                        None => skipping = Some(1),
389                    }
390                    scratch.clear();
391                }
392                Event::Empty(start) => {
393                    if skipping.is_some() {
394                        continue;
395                    }
396                    self.open_element(&start, open.last().copied())?;
397                }
398                Event::End(_) => match skipping.as_mut() {
399                    Some(1) => skipping = None,
400                    Some(depth) => *depth -= 1,
401                    None => {
402                        if let Some(index) = open.pop() {
403                            if !scratch.trim().is_empty() {
404                                let span = self.push_text(&scratch);
405                                if let Some(node) = self.nodes.get_mut(index as usize) {
406                                    node.text = span;
407                                    node.has_text = true;
408                                }
409                            }
410                        }
411                        scratch.clear();
412                    }
413                },
414                Event::Text(text) => {
415                    if skipping.is_some() || open.is_empty() {
416                        continue;
417                    }
418                    let offset = reader.buffer_position();
419                    let decoded = text
420                        .xml_content()
421                        .map_err(|source| ParseError::at_offset(offset, source))?;
422                    scratch.push_str(&decoded);
423                }
424                Event::CData(cdata) => {
425                    if skipping.is_some() || open.is_empty() {
426                        continue;
427                    }
428                    let offset = reader.buffer_position();
429                    let decoded = cdata
430                        .decode()
431                        .map_err(|source| ParseError::at_offset(offset, source))?;
432                    scratch.push_str(&decoded);
433                }
434                Event::GeneralRef(entity) => {
435                    if skipping.is_some() || open.is_empty() {
436                        continue;
437                    }
438                    let offset = reader.buffer_position();
439                    push_entity(&mut scratch, &entity)
440                        .map_err(|source| ParseError::at_offset(offset, source))?;
441                }
442                Event::Eof => break,
443                Event::Decl(_) | Event::PI(_) | Event::Comment(_) | Event::DocType(_) => {}
444            }
445        }
446
447        if self.nodes.is_empty() {
448            return Err(ParseError::new(ParseErrorKind::EmptyDocument));
449        }
450        Ok(())
451    }
452
453    /// Materialises one element.
454    ///
455    /// Returns the new node's index, or `None` when the element opens an out-of-scope
456    /// section whose whole subtree the caller should skip.
457    fn open_element(
458        &mut self,
459        start: &quick_xml::events::BytesStart<'_>,
460        parent: Option<u32>,
461    ) -> Result<Option<u32>, ParseError> {
462        let local = start.local_name();
463        let local = std::str::from_utf8(local.as_ref()).unwrap_or_default();
464        let tag = Tag::from_text(local);
465        if tag.is_skipped_section() {
466            self.skipped_sections.push(local.to_owned());
467            return Ok(None);
468        }
469        let index = self.push_node(tag, local, parent);
470        self.push_attributes(index, start)?;
471        if index == 0 {
472            self.xmlns = element_namespace(start);
473        }
474        Ok(Some(index))
475    }
476
477    fn push_node(&mut self, tag: Tag, local: &str, parent: Option<u32>) -> u32 {
478        // A recognised tag already carries its spelling, so only unknown names go in the
479        // arena. On the largest test file that is most of a megabyte of memcpy avoided.
480        let name = if tag == Tag::Other {
481            self.push_text(local)
482        } else {
483            Span::EMPTY
484        };
485        let index = u32::try_from(self.nodes.len()).unwrap_or(NONE);
486        self.nodes.push(Node {
487            tag,
488            name,
489            parent: parent.unwrap_or(NONE),
490            first_child: NONE,
491            next_sibling: NONE,
492            attr_start: u32::try_from(self.attrs.len()).unwrap_or(0),
493            attr_len: 0,
494            text: Span::EMPTY,
495            has_text: false,
496        });
497        self.last_child.push(NONE);
498
499        if let Some(parent) = parent {
500            match self.last_child.get(parent as usize).copied() {
501                Some(NONE) | None => {
502                    if let Some(node) = self.nodes.get_mut(parent as usize) {
503                        node.first_child = index;
504                    }
505                }
506                Some(previous) => {
507                    if let Some(node) = self.nodes.get_mut(previous as usize) {
508                        node.next_sibling = index;
509                    }
510                }
511            }
512            if let Some(slot) = self.last_child.get_mut(parent as usize) {
513                *slot = index;
514            }
515        }
516        index
517    }
518
519    fn push_attributes(
520        &mut self,
521        index: u32,
522        start: &quick_xml::events::BytesStart<'_>,
523    ) -> Result<(), ParseError> {
524        let start_len = self.attrs.len();
525        for attr in start.attributes() {
526            let attr = attr.map_err(|source| ParseError::new(source.into()))?;
527            let key_bytes = attr.key.as_ref();
528            if key_bytes == b"xmlns" || key_bytes.starts_with(b"xmlns:") {
529                continue;
530            }
531            let key_local = attr.key.local_name();
532            let key_local = std::str::from_utf8(key_local.as_ref()).unwrap_or_default();
533            let value = attr
534                .unescape_value()
535                .map_err(|source| ParseError::new(source.into()))?;
536            let key = AttrKey::from_text(key_local);
537            let name = if key == AttrKey::Other {
538                self.push_text(key_local)
539            } else {
540                Span::EMPTY
541            };
542            let value = self.push_text(&value);
543            self.attrs.push(Attr { key, name, value });
544        }
545        if let Some(node) = self.nodes.get_mut(index as usize) {
546            node.attr_start = u32::try_from(start_len).unwrap_or(0);
547            node.attr_len = u32::try_from(self.attrs.len() - start_len).unwrap_or(0);
548        }
549        Ok(())
550    }
551
552    /// The document element.
553    #[must_use]
554    pub fn root(&self) -> Element<'_> {
555        Element {
556            dom: self,
557            index: 0,
558        }
559    }
560
561    /// Names of sections dropped during parsing, in document order.
562    #[must_use]
563    pub fn skipped_sections(&self) -> &[String] {
564        &self.skipped_sections
565    }
566
567    /// The default XML namespace declared on the root element, if any.
568    #[must_use]
569    pub fn xmlns(&self) -> Option<&str> {
570        self.xmlns.as_deref()
571    }
572
573    /// Number of elements retained in the arena.
574    #[must_use]
575    pub fn len(&self) -> usize {
576        self.nodes.len()
577    }
578
579    /// Whether the arena holds no elements.
580    #[must_use]
581    pub fn is_empty(&self) -> bool {
582        self.nodes.is_empty()
583    }
584}
585
586impl<'d> Element<'d> {
587    fn node(self) -> &'d Node {
588        // The index always comes from this arena, but a missing node degrades to a
589        // detached placeholder rather than panicking.
590        self.dom.nodes.get(self.index as usize).unwrap_or(&DETACHED)
591    }
592
593    /// This element's tag.
594    #[must_use]
595    pub fn tag(self) -> Tag {
596        self.node().tag
597    }
598
599    /// This element's local name as written in the document.
600    #[must_use]
601    pub fn name(self) -> &'d str {
602        let node = self.node();
603        match node.tag {
604            Tag::Other => self.dom.str_at(node.name),
605            tag => tag.text(),
606        }
607    }
608
609    /// The parent element, or `None` at the root.
610    #[must_use]
611    pub fn parent(self) -> Option<Element<'d>> {
612        let parent = self.node().parent;
613        (parent != NONE).then_some(Element {
614            dom: self.dom,
615            index: parent,
616        })
617    }
618
619    /// Direct children, in document order.
620    #[must_use]
621    pub fn children(self) -> Children<'d> {
622        Children {
623            dom: self.dom,
624            next: self.node().first_child,
625        }
626    }
627
628    /// Direct children with the given tag.
629    pub fn children_with(self, tag: Tag) -> impl Iterator<Item = Element<'d>> {
630        self.children().filter(move |child| child.tag() == tag)
631    }
632
633    /// The first direct child with the given tag.
634    #[must_use]
635    pub fn child(self, tag: Tag) -> Option<Element<'d>> {
636        self.children().find(|child| child.tag() == tag)
637    }
638
639    /// The first descendant with the given tag, searched depth-first.
640    ///
641    /// Mirrors the reference implementation's `element.find(".//Tag")`, which is how it
642    /// locates a data encoding anywhere under a parameter type.
643    #[must_use]
644    pub fn descendant(self, tag: Tag) -> Option<Element<'d>> {
645        self.children().find_map(|child| {
646            if child.tag() == tag {
647                Some(child)
648            } else {
649                child.descendant(tag)
650            }
651        })
652    }
653
654    /// The first descendant matching any of `tags`, searched depth-first, preferring the
655    /// shallowest match and then document order.
656    #[must_use]
657    pub fn descendant_any(self, tags: &[Tag]) -> Option<Element<'d>> {
658        for child in self.children() {
659            if tags.contains(&child.tag()) {
660                return Some(child);
661            }
662        }
663        self.children().find_map(|child| child.descendant_any(tags))
664    }
665
666    /// An attribute value by well-known key.
667    #[must_use]
668    pub fn attr(self, key: AttrKey) -> Option<&'d str> {
669        self.attrs_raw()
670            .iter()
671            .find(|attr| attr.key == key)
672            .map(|attr| self.dom.str_at(attr.value))
673    }
674
675    /// An attribute value by literal name, for attributes outside [`AttrKey`].
676    #[must_use]
677    pub fn attr_named(self, name: &str) -> Option<&'d str> {
678        self.attrs_raw()
679            .iter()
680            .find(|attr| self.attr_name(attr) == name)
681            .map(|attr| self.dom.str_at(attr.value))
682    }
683
684    /// Attribute names present on this element, in document order.
685    pub fn attr_names(self) -> impl Iterator<Item = &'d str> {
686        self.attrs_raw()
687            .iter()
688            .map(move |attr| self.attr_name(attr))
689    }
690
691    fn attr_name(self, attr: &Attr) -> &'d str {
692        match attr.key {
693            AttrKey::Other => self.dom.str_at(attr.name),
694            key => key.text(),
695        }
696    }
697
698    fn attrs_raw(self) -> &'d [Attr] {
699        let node = self.node();
700        let start = node.attr_start as usize;
701        let end = start + node.attr_len as usize;
702        self.dom.attrs.get(start..end).unwrap_or_default()
703    }
704
705    /// Text content, if this element has any and no element children.
706    #[must_use]
707    pub fn text(self) -> Option<&'d str> {
708        let node = self.node();
709        node.has_text.then(|| self.dom.str_at(node.text).trim())
710    }
711
712    /// The `/`-joined element path from the root to this element, for diagnostics.
713    #[must_use]
714    pub fn path(self) -> String {
715        let mut parts = Vec::new();
716        let mut cursor = Some(self);
717        while let Some(element) = cursor {
718            parts.push(element.name());
719            cursor = element.parent();
720        }
721        parts.reverse();
722        parts.join("/")
723    }
724}
725
726static DETACHED: Node = Node {
727    tag: Tag::Other,
728    name: Span::EMPTY,
729    parent: NONE,
730    first_child: NONE,
731    next_sibling: NONE,
732    attr_start: 0,
733    attr_len: 0,
734    text: Span::EMPTY,
735    has_text: false,
736};
737
738/// Iterator over the direct children of an element.
739pub struct Children<'d> {
740    dom: &'d Dom,
741    next: u32,
742}
743
744impl<'d> Iterator for Children<'d> {
745    type Item = Element<'d>;
746
747    fn next(&mut self) -> Option<Self::Item> {
748        if self.next == NONE {
749            return None;
750        }
751        let index = self.next;
752        self.next = self
753            .dom
754            .nodes
755            .get(index as usize)
756            .map_or(NONE, |n| n.next_sibling);
757        Some(Element {
758            dom: self.dom,
759            index,
760        })
761    }
762}
763
764impl std::iter::FusedIterator for Children<'_> {}
765
766/// Appends the expansion of a general entity reference to `out`.
767///
768/// The five XML predefined entities and numeric character references are expanded;
769/// anything else (a DTD-declared entity, which XTCE does not use) is written back
770/// literally so that no character data is silently lost.
771fn push_entity(
772    out: &mut String,
773    entity: &quick_xml::events::BytesRef<'_>,
774) -> Result<(), quick_xml::encoding::EncodingError> {
775    if entity.is_char_ref() {
776        if let Ok(Some(ch)) = entity.resolve_char_ref() {
777            out.push(ch);
778            return Ok(());
779        }
780    }
781    let name = entity.decode()?;
782    match name.as_ref() {
783        "amp" => out.push('&'),
784        "lt" => out.push('<'),
785        "gt" => out.push('>'),
786        "apos" => out.push('\''),
787        "quot" => out.push('"'),
788        other => {
789            out.push('&');
790            out.push_str(other);
791            out.push(';');
792        }
793    }
794    Ok(())
795}
796
797/// The namespace URI actually bound to an element's own name.
798///
799/// XTCE documents appear with the vocabulary prefixed (`<xtce:SpaceSystem xmlns:xtce=..>`),
800/// default-namespaced (`<SpaceSystem xmlns=..>`) or with no namespace at all. Only the
801/// binding for *this* element's prefix identifies the XTCE version — picking the first
802/// `xmlns:*` attribute instead would report `xsi` for a document whose only declaration is
803/// the schema-instance one.
804fn element_namespace(start: &quick_xml::events::BytesStart<'_>) -> Option<String> {
805    let qname = start.name();
806    let wanted: Vec<u8> = match qname.prefix() {
807        Some(prefix) => [b"xmlns:".as_slice(), prefix.as_ref()].concat(),
808        None => b"xmlns".to_vec(),
809    };
810    start
811        .attributes()
812        .flatten()
813        .find(|attr| attr.key.as_ref() == wanted.as_slice())
814        .and_then(|attr| String::from_utf8(attr.value.into_owned()).ok())
815}