feedparser-rs 0.8.0

High-performance RSS/Atom/JSON Feed parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Shared parse-context types.
//!
//! Bundles the XML event-loop plumbing (`XmlCtx`) and per-item/per-entry
//! parsing state (`EntryCtx`) that would otherwise be threaded as separate
//! parameters through every RSS/Atom/RSS 1.0 helper function, keeping their
//! signatures under clippy's `too_many_arguments` threshold.

use std::collections::HashMap;
use std::mem::{Discriminant, discriminant};

use quick_xml::{
    Reader,
    errors::SyntaxError,
    events::{BytesEnd, BytesRef, BytesStart, BytesText, Event},
};

use super::common::decode_entity;
use crate::ParserLimits;
use crate::types::ParsedFeed;
use crate::util::base_url::BaseUrlContext;

/// The XML reader of one document plus the defects met while reading it.
///
/// [`Self::read_event_into`] is the only way to read, so an unresolvable entity
/// sets bozo even in skipped content and the element depth stays exact.
///
/// The reader keeps its own stack of open element names and resynchronises on a
/// mismatched end tag: unclosed inner elements are closed with synthesized end
/// events, and an end tag that matches no open element is dropped. A parser therefore
/// always sees properly nested events and a stray tag cannot discard the enclosing item.
pub struct XmlReader<'d> {
    inner: Reader<&'d [u8]>,
    /// The input `inner` was created over; error positions are relative to it.
    input: &'d [u8],
    /// Syntax errors already recovered from, to bound the recovery work.
    recovered: Vec<Discriminant<SyntaxError>>,
    /// Element names that close unclosed inner elements before an item or entry.
    implied_ends: Option<ItemScope>,
    /// An event held back while synthesized end events are emitted first.
    replay: Option<Event<'static>>,
    /// The text that follows a split-off bare ampersand.
    pending_text: Option<String>,
    /// Whether a mismatched end tag forced a resynchronisation.
    resynced: bool,
    /// Names of the open elements, concatenated.
    names: String,
    /// End offset in `names` of each open element, outermost first; its length is the
    /// number of tracked levels, at most `max_tracked`.
    ends: Vec<usize>,
    max_tracked: usize,
    /// Open elements nested deeper than `max_tracked`; their names are not kept.
    untracked: usize,
    /// Synthesized end events still to emit for a resynchronisation.
    pending_ends: usize,
    /// Bit set of the [`Defect`]s recorded so far.
    defects: u8,
    /// The text limit that cut a field, for the [`Defect::TextTruncated`] reason.
    truncated_at: usize,
    xml_error: Option<String>,
}

/// A defect that makes the feed bozo, in the order its reason is preferred.
#[derive(Clone, Copy)]
enum Defect {
    MismatchedEndTag,
    TextTruncated,
    UnresolvedEntity,
    MissingXhtmlDiv,
    ExcessDepth,
    BareAmpersand,
}

impl Defect {
    const BY_PRIORITY: [Self; 6] = [
        Self::MismatchedEndTag,
        Self::TextTruncated,
        Self::UnresolvedEntity,
        Self::MissingXhtmlDiv,
        Self::ExcessDepth,
        Self::BareAmpersand,
    ];

    const fn bit(self) -> u8 {
        1 << self as u8
    }

    const fn reason(self) -> &'static str {
        match self {
            Self::MismatchedEndTag => "Mismatched or unmatched end tag",
            Self::TextTruncated => "Text field exceeds maximum length",
            Self::UnresolvedEntity => "Unresolvable entity in text",
            Self::MissingXhtmlDiv => "xhtml text construct without a div wrapper",
            Self::ExcessDepth => "XML nesting depth exceeds maximum inside a text element",
            Self::BareAmpersand => "Bare ampersand in text",
        }
    }
}

/// Names that scope the implied end tags before an item or entry.
///
/// An item start tag that arrives while elements other than `container` are open
/// closes them, because an item is always a direct child of its container. An item
/// name nested below another open element that is not the item itself belongs to
/// foreign or xhtml content and closes nothing.
#[derive(Clone, Copy, Debug)]
pub struct ItemScope {
    /// Name of the item element (`item` or `entry`).
    pub item: &'static str,
    /// Which part of an element name must equal `item`.
    pub naming: ItemName,
    /// Local name of the outermost open element that holds the items (`channel`, `RDF`
    /// or `feed`), so a same-named element inside content is not mistaken for it.
    pub container: &'static str,
    /// Local name of an element that is never closed implicitly (RSS 1.0 `channel`).
    pub barrier: Option<&'static str>,
}

/// How an element name is compared with the item name of a format.
///
/// It mirrors the dispatcher of each format, so the reader never treats as an item
/// an element that the parser would skip.
#[derive(Clone, Copy, Debug)]
pub enum ItemName {
    /// The whole qualified name, so `x:item` is not an item.
    Qualified,
    /// The part after the prefix, so `rss:item` is an item.
    Local,
}

impl ItemScope {
    fn is_item(&self, name: &str) -> bool {
        match self.naming {
            ItemName::Qualified => name == self.item,
            ItemName::Local => local_name(name) == self.item,
        }
    }
}

/// Runs `pass` and, when it had to resynchronise, runs it again with implied end tags.
///
/// Implied end tags would change a well-formed document that carries an item-named
/// element inside foreign or xhtml content, so they are enabled only for a document
/// that is already broken, and the second result is kept only if it has more entries.
pub fn parse_with_implied_ends(
    scope: ItemScope,
    mut pass: impl FnMut(Option<ItemScope>) -> (ParsedFeed, bool),
) -> ParsedFeed {
    let (first, resynced) = pass(None);
    if !resynced {
        return first;
    }
    let (second, _) = pass(Some(scope));
    if second.entries.len() > first.entries.len() {
        second
    } else {
        first
    }
}

fn local_name(name: &str) -> &str {
    name.rsplit_once(':').map_or(name, |(_, local)| local)
}

impl<'d> XmlReader<'d> {
    /// Creates a reader over `data` tracking as many levels as the default nesting limit.
    #[cfg(test)]
    pub fn new(data: &'d [u8]) -> Self {
        Self::with_limits(data, &ParserLimits::default())
    }

    /// Creates a reader over `data` tracking `limits.max_nesting_depth` levels.
    pub fn with_limits(data: &'d [u8], limits: &ParserLimits) -> Self {
        let mut inner = Reader::from_reader(data);
        let config = inner.config_mut();
        config.check_end_names = false;
        config.allow_unmatched_ends = true;
        config.allow_dangling_amp = true;
        Self {
            inner,
            input: data,
            recovered: Vec::new(),
            implied_ends: None,
            replay: None,
            pending_text: None,
            resynced: false,
            names: String::new(),
            ends: Vec::new(),
            max_tracked: limits.max_nesting_depth,
            untracked: 0,
            pending_ends: 0,
            defects: 0,
            truncated_at: 0,
            xml_error: None,
        }
    }

    /// Enables implied end tags before an item or entry for this reader.
    #[must_use]
    pub const fn with_implied_ends(mut self, scope: Option<ItemScope>) -> Self {
        self.implied_ends = scope;
        self
    }

    /// Whether a mismatched end tag forced a resynchronisation.
    ///
    /// Recovery from unreadable markup does not count: it needs no second pass.
    pub const fn resynced(&self) -> bool {
        self.resynced
    }

    /// Reads the next event, recording an entity reference that cannot be resolved.
    ///
    /// The events are properly nested: see the type documentation. A bare ampersand
    /// is reported as an `amp` reference, and markup that cannot be read is skipped up
    /// to the next `<`; both set bozo.
    ///
    /// # Errors
    ///
    /// Returns the XML error when the rest of the input cannot be read.
    pub fn read_event_into<'b>(&mut self, buf: &'b mut Vec<u8>) -> quick_xml::Result<Event<'b>> {
        if let Some(event) = self.next_synthesized() {
            return Ok(event);
        }
        let before = self.inner.buffer_position();
        match self.inner.read_event_into(buf) {
            Ok(event) => Ok(self.track(event)),
            Err(error) => self.recover(error, before),
        }
    }

    fn next_synthesized<'b>(&mut self) -> Option<Event<'b>> {
        if self.pending_ends > 0 {
            self.pending_ends -= 1;
            return Some(Event::End(self.synthesized_end()));
        }
        if let Some(text) = self.pending_text.take() {
            return Some(Event::Text(BytesText::from_escaped(text)));
        }
        let event = self.replay.take()?;
        if let Event::Start(start) = &event {
            self.open(start.name().as_ref());
        }
        Some(event)
    }

    fn track<'b>(&mut self, event: Event<'b>) -> Event<'b> {
        let implied = match &event {
            Event::Start(start) | Event::Empty(start) => self.implied_closes(start),
            _ => 0,
        };
        if implied > 0 {
            self.resync(implied);
            self.replay = Some(event.into_owned());
            return Event::End(self.synthesized_end());
        }
        match &event {
            Event::Start(start) => self.open(start.name().as_ref()),
            Event::End(end) => match self.close(end.name().as_ref()) {
                EndAction::Pass => {}
                EndAction::Resync(unclosed) => {
                    self.resync(self.untracked + unclosed + 1);
                    return Event::End(self.synthesized_end());
                }
                // An empty text event stands in for the dropped tag.
                EndAction::Drop => {
                    self.record(Defect::MismatchedEndTag);
                    return Event::Text(BytesText::new(""));
                }
            },
            Event::GeneralRef(reference) if decode_entity(reference).is_none() => {
                self.record(Defect::UnresolvedEntity);
            }
            Event::Text(text) if text.starts_with('&') => return self.split_bare_ampersand(text),
            _ => {}
        }
        event
    }

    /// Records a resynchronisation that emits `ends` synthesized end events in total.
    const fn resync(&mut self, ends: usize) {
        self.record(Defect::MismatchedEndTag);
        self.resynced = true;
        self.pending_ends = ends - 1;
    }

    /// Number of open elements to close before an item or entry start tag, 0 if none.
    fn implied_closes(&self, start: &BytesStart<'_>) -> usize {
        let Some(scope) = self.implied_ends else {
            return 0;
        };
        if !scope.is_item(start.name().as_ref()) {
            return 0;
        }
        let Some(container) = (0..self.ends.len())
            .rev()
            .find(|&from_top| local_name(self.name_from_top(from_top)) == scope.container)
        else {
            return 0;
        };
        let name_at = |from_top| self.name_from_top(from_top);
        let barred = (0..container).any(|from_top| {
            scope
                .barrier
                .is_some_and(|b| local_name(name_at(from_top)) == b)
        });
        if barred || (1..container).any(|from_top| scope.is_item(name_at(from_top))) {
            return 0;
        }
        container + self.untracked
    }

    /// Turns the text of a bare ampersand into an `amp` reference followed by the rest.
    fn split_bare_ampersand<'b>(&mut self, text: &BytesText<'_>) -> Event<'b> {
        self.record(Defect::BareAmpersand);
        if let Some(rest) = text.strip_prefix('&').filter(|rest| !rest.is_empty()) {
            self.pending_text = Some(rest.to_owned());
        }
        Event::GeneralRef(BytesRef::new("amp"))
    }

    /// Recovers from a read error by skipping to the next `<`, if the error allows it.
    ///
    /// An ill-formed construct is replaced by an empty text event. A syntax error ends
    /// the inner reader, so a new one is started at the next `<`; each kind of syntax
    /// error is recovered once, because its terminator is then missing from the rest of
    /// the input and the same failure again is final.
    fn recover<'b>(
        &mut self,
        error: quick_xml::Error,
        before: u64,
    ) -> quick_xml::Result<Event<'b>> {
        let recovered = match &error {
            quick_xml::Error::IllFormed(_) => self.inner.buffer_position() > before,
            quick_xml::Error::Syntax(kind) => self.restart_after(*kind),
            _ => false,
        };
        if !recovered {
            return Err(error);
        }
        self.record_xml_error(&error);
        Ok(Event::Text(BytesText::new("")))
    }

    fn restart_after(&mut self, kind: SyntaxError) -> bool {
        let seen = discriminant(&kind);
        if self.recovered.contains(&seen) {
            return false;
        }
        let from = usize::try_from(self.inner.error_position()).map_or(usize::MAX, |at| at + 1);
        let Some(offset) = self
            .input
            .get(from..)
            .and_then(|rest| rest.iter().position(|&b| b == b'<'))
        else {
            return false;
        };
        self.recovered.push(seen);
        self.input = &self.input[from + offset..];
        let config = self.inner.config().clone();
        self.inner = Reader::from_reader(self.input);
        *self.inner.config_mut() = config;
        true
    }

    fn open(&mut self, name: &str) {
        if self.ends.len() < self.max_tracked {
            self.names.push_str(name);
            self.ends.push(self.names.len());
        } else {
            self.untracked += 1;
        }
    }

    /// Decides what to do with an end tag named `name` and updates the stack.
    ///
    /// Elements nested beyond the cap have no recorded name, so an end tag that names a
    /// tracked element other than the innermost one is taken to close everything inside
    /// it; any other end tag closes one untracked element.
    fn close(&mut self, name: &str) -> EndAction {
        let matched = (0..self.ends.len()).find(|&from_top| self.name_from_top(from_top) == name);
        match matched {
            Some(unclosed) if unclosed > 0 => EndAction::Resync(unclosed),
            _ if self.untracked > 0 => {
                self.untracked -= 1;
                EndAction::Pass
            }
            Some(_) => {
                self.pop_name();
                EndAction::Pass
            }
            None => EndAction::Drop,
        }
    }

    /// The name of the open element `from_top` levels below the innermost one.
    fn name_from_top(&self, from_top: usize) -> &str {
        let index = self.ends.len() - 1 - from_top;
        let start = index.checked_sub(1).map_or(0, |prev| self.ends[prev]);
        self.names.get(start..self.ends[index]).unwrap_or_default()
    }

    /// Drops the innermost open element without allocating.
    fn pop_name(&mut self) {
        let start = self
            .ends
            .len()
            .checked_sub(2)
            .map_or(0, |prev| self.ends[prev]);
        self.ends.pop();
        self.names.truncate(start);
    }

    /// An end event for the innermost open element.
    ///
    /// An untracked element has no name; its end event carries an empty one.
    fn synthesized_end(&mut self) -> BytesEnd<'static> {
        if self.untracked > 0 {
            self.untracked -= 1;
            return BytesEnd::new("");
        }
        let name = self.name_from_top(0).to_owned();
        self.pop_name();
        BytesEnd::new(name)
    }

    /// Records an XML error that the caller recovers from instead of returning.
    pub fn record_xml_error(&mut self, error: &quick_xml::Error) {
        self.xml_error
            .get_or_insert_with(|| format!("XML parsing error: {error}"));
    }

    /// Number of elements currently open.
    pub const fn depth(&self) -> usize {
        self.ends.len() + self.untracked
    }

    /// Records markup inside a text element that exceeds the nesting limit.
    pub const fn record_excess_depth(&mut self) {
        self.record(Defect::ExcessDepth);
    }

    /// Records a text field cut to `max_text_length`.
    pub const fn record_text_truncated(&mut self, max_len: usize) {
        self.truncated_at = max_len;
        self.record(Defect::TextTruncated);
    }

    /// Records an xhtml text construct that lacks its `<div>` wrapper.
    pub const fn record_missing_xhtml_div(&mut self) {
        self.record(Defect::MissingXhtmlDiv);
    }

    /// Whether an xhtml text construct without a wrapper was recorded.
    #[cfg(test)]
    pub const fn missing_xhtml_div(&self) -> bool {
        self.has(Defect::MissingXhtmlDiv)
    }

    #[cfg(test)]
    const fn has_mismatched_end_tag(&self) -> bool {
        self.has(Defect::MismatchedEndTag)
    }

    const fn record(&mut self, defect: Defect) {
        self.defects |= defect.bit();
    }

    const fn has(&self, defect: Defect) -> bool {
        self.defects & defect.bit() != 0
    }

    /// Marks `feed` as bozo if any defect was recorded.
    ///
    /// An earlier, more specific `bozo_exception` is kept.
    pub fn report_defects(&self, feed: &mut ParsedFeed) {
        let reason = if let Some(error) = &self.xml_error {
            error.clone()
        } else if let Some(defect) = Defect::BY_PRIORITY.into_iter().find(|&d| self.has(d)) {
            match defect {
                Defect::TextTruncated => {
                    format!("{} of {} bytes", defect.reason(), self.truncated_at)
                }
                other => other.reason().to_string(),
            }
        } else {
            return;
        };
        feed.bozo = true;
        feed.bozo_exception.get_or_insert(reason);
    }
}

/// What the reader does with an end tag.
enum EndAction {
    /// The tag closes the innermost open element.
    Pass,
    /// The tag closes an element this many levels down; the levels above are unclosed.
    Resync(usize),
    /// The tag matches no open element.
    Drop,
}

/// XML event-loop plumbing shared by every parser helper.
///
/// Carries the reader, its reusable event buffer, and the active
/// [`ParserLimits`]. Every helper that consumes XML events borrows the
/// `reader`/`buf` pair from here instead of taking them as separate
/// parameters.
pub struct XmlCtx<'r, 'd> {
    /// The XML event reader positioned at the current parse location.
    pub reader: &'r mut XmlReader<'d>,
    /// Reusable buffer for `reader.read_event_into`; cleared between events.
    pub buf: &'r mut Vec<u8>,
    /// Parser resource limits (nesting depth, text length, entry count, ...).
    pub limits: &'r ParserLimits,
}

impl<'d> XmlCtx<'_, 'd> {
    /// Reborrow this context for a nested call.
    ///
    /// Required because [`EntryCtx`] holds `XmlCtx` by value while the
    /// caller must retain use of its own `reader`/`buf` afterwards.
    pub const fn reborrow(&mut self) -> XmlCtx<'_, 'd> {
        XmlCtx {
            reader: &mut *self.reader,
            buf: &mut *self.buf,
            limits: self.limits,
        }
    }
}

/// Per-item (RSS/RSS 1.0) or per-entry (Atom) parsing context.
///
/// Built at the top of `parse_item`/`parse_entry` — never by the caller,
/// since the caller holds `feed: &mut ParsedFeed` and this context borrows
/// `&feed.namespaces` for its lifetime. Carries the read-only context
/// (namespaces, xml:base, xml:lang) plus accumulators written while walking
/// an item/entry's children.
pub struct EntryCtx<'r, 'd, 'p> {
    /// XML event-loop plumbing (reader, buffer, limits).
    pub xml: XmlCtx<'r, 'd>,
    /// The xml:base resolution context inherited from the enclosing feed/channel.
    pub base: &'p BaseUrlContext,
    /// The effective xml:lang for this item/entry, if any.
    pub lang: Option<&'p str>,
    /// Declared namespace prefix -> URI mapping for the whole feed.
    pub namespaces: &'p HashMap<String, String>,
    /// Bozo accumulator (entity-resolution errors, GML coordinate/dims
    /// mismatches, ...), returned to the caller once the item/entry has been
    /// fully parsed.
    pub bozo: bool,
    /// Specific description for `bozo`, set only by the `GeoRSS` GML
    /// `srsDimension`-mismatch case (currently the sole writer); the flush
    /// site falls back to a generic "unresolvable entity" description when
    /// this is `None`. Not a general first-set-wins arbiter across every
    /// bozo cause in the item/entry — an unrelated entity-resolution error
    /// elsewhere in the same item/entry does not compete with this field for
    /// which description wins; the GML message always takes precedence over
    /// the generic fallback when both occurred, regardless of document order.
    pub bozo_reason: Option<&'static str>,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Reads every event of `xml` and renders start tags as `<n>`, end tags as `</n>`.
    fn trace<'d>(xml: &'d [u8], limits: &ParserLimits) -> (String, XmlReader<'d>) {
        let mut reader = XmlReader::with_limits(xml, limits);
        let mut buf = Vec::new();
        let mut tags = Vec::new();
        loop {
            buf.clear();
            match reader.read_event_into(&mut buf).unwrap() {
                Event::Start(e) => tags.push(format!("<{}>", e.name().as_ref())),
                Event::End(e) => tags.push(format!("</{}>", e.name().as_ref())),
                Event::Eof => break,
                _ => {}
            }
        }
        (tags.concat(), reader)
    }

    #[test]
    fn unclosed_inner_elements_get_synthesized_ends() {
        let (out, reader) = trace(b"<a><b><c>x</b></a>", &ParserLimits::default());
        assert_eq!(out, "<a><b><c></c></b></a>");
        assert!(reader.has_mismatched_end_tag());
        assert_eq!(reader.depth(), 0);
    }

    #[test]
    fn unmatched_end_tags_are_dropped() {
        let (out, reader) = trace(b"<a></x></y></a></z>", &ParserLimits::default());
        assert_eq!(out, "<a></a>");
        assert!(reader.has_mismatched_end_tag());
    }

    #[test]
    fn well_formed_input_reports_no_defect() {
        let (out, reader) = trace(b"<a><b/><c></c></a>", &ParserLimits::default());
        assert_eq!(out, "<a><c></c></a>");
        assert!(!reader.has_mismatched_end_tag());
    }

    #[test]
    fn levels_beyond_the_cap_are_counted_not_tracked() {
        let limits = ParserLimits::default().with_max_nesting_depth(2);
        let (out, reader) = trace(b"<a><b><c><d></d></c></b></a>", &limits);
        assert_eq!(out, "<a><b><c><d></d></c></b></a>");
        assert!(!reader.has_mismatched_end_tag());
        assert_eq!(reader.depth(), 0);
    }

    #[test]
    fn end_tag_of_an_outer_element_closes_untracked_levels_too() {
        let limits = ParserLimits::default().with_max_nesting_depth(2);
        let (out, reader) = trace(b"<a><b><c><c></a>", &limits);
        assert_eq!(out, "<a><b><c><c></></></b></a>");
        assert!(reader.has_mismatched_end_tag());
        assert_eq!(reader.depth(), 0);
    }

    #[test]
    fn the_cap_is_exclusive_of_one_more_level() {
        let limits = ParserLimits::default().with_max_nesting_depth(2);
        // Both levels are tracked at the cap, so the names are recovered.
        let (at_cap, _) = trace(b"<a><b></a>", &limits);
        assert_eq!(at_cap, "<a><b></b></a>");
        // The third level is untracked: its end is synthesized without a name.
        let (beyond, _) = trace(b"<a><b><c></a>", &limits);
        assert_eq!(beyond, "<a><b><c></></b></a>");
    }

    const ITEM_SCOPE: ItemScope = ItemScope {
        item: "item",
        naming: ItemName::Qualified,
        container: "channel",
        barrier: None,
    };

    fn trace_implied(xml: &[u8], limits: &ParserLimits) -> (String, bool) {
        let mut reader = XmlReader::with_limits(xml, limits).with_implied_ends(Some(ITEM_SCOPE));
        let mut buf = Vec::new();
        let mut tags = Vec::new();
        loop {
            buf.clear();
            match reader.read_event_into(&mut buf).unwrap() {
                Event::Start(e) => tags.push(format!("<{}>", e.name().as_ref())),
                Event::Empty(e) => tags.push(format!("<{}/>", e.name().as_ref())),
                Event::End(e) => tags.push(format!("</{}>", e.name().as_ref())),
                Event::Eof => break,
                _ => {}
            }
        }
        (tags.concat(), reader.resynced())
    }

    #[test]
    fn item_closes_unclosed_children_of_the_container() {
        let (out, resynced) = trace_implied(
            b"<channel><foo><bar><item/></channel>",
            &ParserLimits::default(),
        );
        assert_eq!(out, "<channel><foo><bar></bar></foo><item/></channel>");
        assert!(resynced);
    }

    #[test]
    fn item_directly_inside_the_container_is_not_replayed() {
        let (out, resynced) = trace_implied(
            b"<channel><item></item></channel>",
            &ParserLimits::default(),
        );
        assert_eq!(out, "<channel><item></item></channel>");
        assert!(!resynced);
    }

    #[test]
    fn implied_ends_count_untracked_levels() {
        let limits = ParserLimits::default().with_max_nesting_depth(2);
        let (out, resynced) = trace_implied(b"<channel><a><b><item></item></channel>", &limits);
        assert_eq!(out, "<channel><a><b></></a><item></item></channel>");
        assert!(resynced);
    }

    #[test]
    fn prefixed_item_name_is_not_an_item_for_qualified_naming() {
        let (out, resynced) = trace_implied(
            b"<channel><foo><x:item/></channel>",
            &ParserLimits::default(),
        );
        assert_eq!(out, "<channel><foo><x:item/></foo></channel>");
        assert!(resynced);
    }

    #[test]
    fn item_nested_in_foreign_content_below_an_item_closes_nothing() {
        let (out, _) = trace_implied(
            b"<channel><item><p><item/></p></item></channel>",
            &ParserLimits::default(),
        );
        assert_eq!(out, "<channel><item><p><item/></p></item></channel>");
    }

    #[test]
    fn local_naming_accepts_a_prefixed_item() {
        let scope = ItemScope {
            naming: ItemName::Local,
            ..ITEM_SCOPE
        };
        let mut reader =
            XmlReader::new(b"<channel><foo><r:item/></channel>").with_implied_ends(Some(scope));
        let mut buf = Vec::new();
        let mut tags = Vec::new();
        loop {
            buf.clear();
            match reader.read_event_into(&mut buf).unwrap() {
                Event::End(e) => tags.push(format!("</{}>", e.name().as_ref())),
                Event::Eof => break,
                _ => {}
            }
        }
        assert_eq!(tags, ["</foo>", "</channel>"]);
    }

    fn feed_titled(title: &str, entries: usize) -> ParsedFeed {
        let mut feed = ParsedFeed::new();
        feed.feed.title = Some(title.into());
        feed.entries.resize_with(entries, Default::default);
        feed
    }

    #[test]
    fn second_pass_wins_only_with_strictly_more_entries() {
        let passes = |second: usize| {
            parse_with_implied_ends(ITEM_SCOPE, |implied| match implied {
                None => (feed_titled("first", 2), true),
                Some(_) => (feed_titled("second", second), true),
            })
        };
        assert_eq!(passes(2).feed.title.as_deref(), Some("first"));
        assert_eq!(passes(3).feed.title.as_deref(), Some("second"));
    }

    #[test]
    fn second_pass_is_skipped_without_a_resync() {
        let feed = parse_with_implied_ends(ITEM_SCOPE, |implied| {
            assert!(implied.is_none());
            (feed_titled("first", 0), false)
        });
        assert_eq!(feed.feed.title.as_deref(), Some("first"));
    }

    #[test]
    fn bare_ampersand_is_split_into_a_reference_and_the_rest() {
        let mut reader = XmlReader::new(b"<a>AT&T</a>");
        let mut buf = Vec::new();
        let mut seen = Vec::new();
        loop {
            buf.clear();
            match reader.read_event_into(&mut buf).unwrap() {
                Event::Text(t) => seen.push(format!("text:{}", &*t)),
                Event::GeneralRef(r) => seen.push(format!("ref:{}", r.as_ref())),
                Event::Eof => break,
                _ => {}
            }
        }
        assert_eq!(seen, ["text:AT", "ref:amp", "text:T"]);
        assert!(reader.has(Defect::BareAmpersand));
    }

    #[test]
    fn syntax_error_resumes_at_the_next_markup_once_per_kind() {
        let mut reader = XmlReader::new(b"<a><!-- x <b>t</b></a>");
        let mut buf = Vec::new();
        let mut tags = Vec::new();
        loop {
            buf.clear();
            match reader.read_event_into(&mut buf).unwrap() {
                Event::Start(e) => tags.push(e.name().as_ref().to_owned()),
                Event::Eof => break,
                _ => {}
            }
        }
        assert_eq!(tags, ["a", "b"]);
        assert!(!reader.resynced());
    }

    #[test]
    fn container_is_the_outermost_open_element_of_that_name() {
        let (out, _) = trace_implied(
            b"<channel><foo><channel><item/></channel></foo></channel>",
            &ParserLimits::default(),
        );
        assert_eq!(
            out,
            "<channel><foo><channel></channel></foo><item/></channel>"
        );
    }

    #[test]
    fn barrier_element_is_not_closed_implicitly() {
        let scope = ItemScope {
            barrier: Some("channel"),
            container: "RDF",
            ..ITEM_SCOPE
        };
        let mut reader =
            XmlReader::new(b"<RDF><channel><item/></channel></RDF>").with_implied_ends(Some(scope));
        let mut buf = Vec::new();
        loop {
            buf.clear();
            if matches!(reader.read_event_into(&mut buf).unwrap(), Event::Eof) {
                break;
            }
        }
        assert!(!reader.resynced());
    }

    #[test]
    fn structural_defect_outranks_a_bare_ampersand() {
        let mut reader = XmlReader::new(b"<a><b>AT&T</a>");
        let mut buf = Vec::new();
        loop {
            buf.clear();
            if matches!(reader.read_event_into(&mut buf).unwrap(), Event::Eof) {
                break;
            }
        }
        let mut feed = ParsedFeed::new();
        reader.report_defects(&mut feed);
        assert_eq!(
            feed.bozo_exception.as_deref(),
            Some("Mismatched or unmatched end tag")
        );
    }

    #[test]
    fn depth_counts_tracked_and_untracked_levels() {
        let limits = ParserLimits::default().with_max_nesting_depth(2);
        let xml = b"<a><b><c><d></d></c></b></a>";
        let mut reader = XmlReader::with_limits(xml, &limits);
        let mut buf = Vec::new();
        let mut depths = Vec::new();
        loop {
            buf.clear();
            let event = reader.read_event_into(&mut buf).unwrap();
            if matches!(event, Event::Eof) {
                break;
            }
            depths.push(reader.depth());
        }
        assert_eq!(depths, [1, 2, 3, 4, 3, 2, 1, 0]);
    }
}