qso-graph-trust 0.2.0

Sign ADIF logs for ARRL's Logbook of The World (LoTW)
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
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 the QSO Graph Trust contributors (see AUTHORS). Part of QSO Graph Trust; see LICENSE.

//! A reader for the XML TQSL writes, and nothing more: elements, attributes, text, comments and an
//! XML declaration. A DTD, CDATA, processing instructions after the declaration, and any entity but
//! XML's five and character references are refused, so nothing can expand; so is any character XML
//! does not allow. Declarations follow XML 1.0 with UTF-8 encoding; comments cannot contain `--`
//! or end in `-`, and character data cannot contain `]]>`. Text and attribute values are normalized
//! as XML says: line ends become `\n`, and
//! in an attribute each literal tab or line end becomes a space.
//!
//! It reads untrusted input that can hold private keys, so it is bounded as it goes, never after:
//! depth, elements and attributes are counted and stopped at their limits, with nothing allocated in
//! proportion to anything else. It reads iteratively, so depth cannot overflow the stack. Text and
//! attribute values are borrowed from the input; decoding one copies it once, into a buffer made at
//! its final size and wiped when dropped.

use std::fmt;

use zeroize::Zeroizing;

/// The deepest nesting read.
pub const MAX_DEPTH: usize = 16;
/// The most elements read.
pub const MAX_ELEMENTS: usize = 2_000_000;
/// The most attributes on one element.
pub const MAX_ATTRIBUTES: usize = 64;

/// Additional limits for a document format. Named counts apply across the whole document;
/// value limits count decoded UTF-8 bytes, including text split by comments.
pub struct Limits<'a> {
    pub elements: usize,
    pub elements_named: &'a [(&'a str, usize)],
    pub attribute_len: fn(element: &str, attribute: &str) -> usize,
    pub text_len: fn(element: &str) -> usize,
}

/// Why XML could not be read: where, as a line and column from 1, and what kind of problem.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct XmlError {
    pub line: usize,
    pub column: usize,
    pub problem: &'static str,
}

impl fmt::Display for XmlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} at line {}, column {}",
            self.problem, self.line, self.column
        )
    }
}

impl std::error::Error for XmlError {}

/// One element: its name, its attributes, the text directly inside it and its child elements, all
/// borrowing from the input.
#[derive(Debug, Default)]
pub struct Element<'a> {
    pub name: &'a str,
    attributes: Vec<(&'a str, &'a str)>,
    text: Vec<&'a str>,
    text_len: usize,
    text_after_cr: bool,
    pub children: Vec<Element<'a>>,
}

impl<'a> Element<'a> {
    /// An attribute's value, decoded; `None` if it is not there.
    pub fn attribute(&self, name: &str) -> Option<Zeroizing<String>> {
        self.attributes
            .iter()
            .find(|(n, _)| *n == name)
            .map(|(_, v)| decode([*v].into_iter(), true))
    }

    /// Decode only if the value fits, without allocating an oversized buffer.
    pub fn attribute_bounded(
        &self,
        name: &str,
        max: usize,
    ) -> Result<Option<Zeroizing<String>>, &'static str> {
        self.attributes
            .iter()
            .find(|(n, _)| *n == name)
            .map(|(_, v)| decode_bounded([*v].into_iter(), true, max))
            .transpose()
    }

    /// Attribute names without decoding or allocating their values.
    pub fn attribute_names(&self) -> impl Iterator<Item = &'a str> + '_ {
        self.attributes.iter().map(|(n, _)| *n)
    }

    /// The attributes' names and decoded values, in the order written.
    pub fn attributes(&self) -> impl Iterator<Item = (&'a str, Zeroizing<String>)> + '_ {
        self.attributes
            .iter()
            .map(|(n, v)| (*n, decode([*v].into_iter(), true)))
    }

    /// The text directly inside the element, decoded, comments left out.
    pub fn text(&self) -> Zeroizing<String> {
        decode(self.text.iter().copied(), false)
    }

    /// Decode only if all text pieces together fit the cap.
    pub fn text_bounded(&self, max: usize) -> Result<Zeroizing<String>, &'static str> {
        decode_bounded(self.text.iter().copied(), false, max)
    }

    /// The child elements with this name.
    pub fn children_named<'s>(&'s self, name: &'s str) -> impl Iterator<Item = &'s Element<'a>> {
        self.children.iter().filter(move |c| c.name == name)
    }
}

/// Decodes text already checked by the reader, as XML 1.0 does (sections 2.11 and 3.3.3): a line end
/// (`\r\n` or a lone `\r`) becomes `\n`, and in an attribute each literal tab or line end becomes a
/// space; then XML's five entities and character references, whose characters are kept as they are
/// (found in review: `HOME<tab>A` and `HOME A` were two names).
fn decode<'a>(pieces: impl Iterator<Item = &'a str> + Clone, attribute: bool) -> Zeroizing<String> {
    decode_bounded(pieces, attribute, usize::MAX).expect("reader checked the values")
}

fn decode_bounded<'a>(
    pieces: impl Iterator<Item = &'a str> + Clone,
    attribute: bool,
    max: usize,
) -> Result<Zeroizing<String>, &'static str> {
    let len = decoded_len(pieces.clone(), attribute, max, &mut false)?;
    // Count before allocating, and reserve decoded bytes rather than the potentially much larger
    // entity-encoded input. The second pass cannot grow this buffer.
    let mut out = Zeroizing::new(String::with_capacity(len));
    walk_decoded(pieces, attribute, &mut false, |c| {
        out.push(c);
        Ok(())
    })?;
    Ok(out)
}

fn decoded_len<'a>(
    pieces: impl Iterator<Item = &'a str>,
    attribute: bool,
    max: usize,
    after_cr: &mut bool,
) -> Result<usize, &'static str> {
    let mut len = 0usize;
    walk_decoded(pieces, attribute, after_cr, |c| {
        if c.len_utf8() > max - len {
            return Err("value too long");
        }
        len += c.len_utf8();
        Ok(())
    })?;
    Ok(len)
}

fn walk_decoded<'a>(
    pieces: impl Iterator<Item = &'a str>,
    attribute: bool,
    after_cr: &mut bool,
    mut emit: impl FnMut(char) -> Result<(), &'static str>,
) -> Result<(), &'static str> {
    for piece in pieces {
        let mut chars = piece.char_indices();
        while let Some((i, c)) = chars.next() {
            let was_cr = std::mem::replace(after_cr, c == '\r');
            match c {
                '\n' if was_cr => {}
                '\r' | '\n' => emit(if attribute { ' ' } else { '\n' })?,
                '\t' if attribute => emit(' ')?,
                '&' => {
                    let rest = &piece[i + 1..];
                    let semi = rest.find(';').ok_or("unknown entity")?;
                    emit(entity(&rest[..semi]).ok_or("unknown entity")?)?;
                    for _ in 0..semi + 1 {
                        chars.next();
                    }
                }
                c => emit(c)?,
            }
        }
    }
    Ok(())
}

/// The character an entity names: XML's five, or a character reference (`&#` decimal digits, or
/// `&#x` hexadecimal ones) to a character XML allows.
fn entity(name: &str) -> Option<char> {
    match name {
        "lt" => Some('<'),
        "gt" => Some('>'),
        "amp" => Some('&'),
        "quot" => Some('"'),
        "apos" => Some('\''),
        _ => {
            let number = name.strip_prefix('#')?;
            let (digits, radix) = match number.strip_prefix('x') {
                Some(hex) => (hex, 16),
                None => (number, 10),
            };
            // Digits only: `+` and `-`, which the parser would take, are not XML's.
            if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
                return None;
            }
            char::from_u32(u32::from_str_radix(digits, radix).ok()?).filter(|&c| is_xml_char(c))
        }
    }
}

/// Whether XML 1.0 allows a character (section 2.2): tab, line ends, and everything from space up
/// but U+FFFE and U+FFFF (a `char` cannot be a surrogate).
fn is_xml_char(c: char) -> bool {
    matches!(c, '\t' | '\n' | '\r') || (c >= ' ' && c != '\u{fffe}' && c != '\u{ffff}')
}

fn is_name_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_'
}

fn is_name(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ':')
}

struct Reader<'a> {
    input: &'a str,
    at: usize,
}

impl<'a> Reader<'a> {
    fn error(&self, problem: &'static str) -> XmlError {
        let before = &self.input[..self.at];
        let line = before.matches('\n').count() + 1;
        let column = before.rsplit('\n').next().map_or(0, |l| l.chars().count()) + 1;
        XmlError {
            line,
            column,
            problem,
        }
    }

    fn rest(&self) -> &'a str {
        &self.input[self.at..]
    }

    fn skip_space(&mut self) {
        let rest = self.rest();
        self.at += rest.len() - rest.trim_start_matches([' ', '\t', '\r', '\n']).len();
    }

    /// Past `end`, which must come.
    fn past(&mut self, end: &str, problem: &'static str) -> Result<&'a str, XmlError> {
        let found = self.rest().find(end).ok_or_else(|| self.error(problem))?;
        let skipped = &self.rest()[..found];
        self.at += found + end.len();
        Ok(skipped)
    }

    fn name(&mut self) -> Result<&'a str, XmlError> {
        let rest = self.rest();
        if !rest.starts_with(is_name_start) {
            return Err(self.error("a name was expected"));
        }
        let len = rest.find(|c: char| !is_name(c)).unwrap_or(rest.len());
        self.at += len;
        Ok(&rest[..len])
    }

    /// XML 1.0 sections 2.8 and 4.3.3: ordered, quoted pseudo-attributes, without references.
    /// This reader accepts UTF-8 only, and never allocates declaration-sized buffers.
    fn declaration(&mut self) -> Result<(), XmlError> {
        if self.rest().find("?>").is_some_and(|end| end > 64 * 1024) {
            return Err(self.error("the XML declaration is too long"));
        }
        self.at += 5; // <?xml
        let mut version = false;
        let mut encoding = false;
        let mut standalone = false;
        loop {
            let before = self.at;
            self.skip_space();
            if self.rest().starts_with("?>") && version {
                self.at += 2;
                return Ok(());
            }
            if before == self.at {
                return Err(self.error("invalid XML declaration"));
            }
            let name = self
                .name()
                .map_err(|_| self.error("invalid XML declaration"))?;
            self.skip_space();
            if !self.rest().starts_with('=') {
                return Err(self.error("invalid XML declaration"));
            }
            self.at += 1;
            self.skip_space();
            let quote = match self.rest().chars().next() {
                Some(q @ ('\'' | '"')) => q,
                _ => return Err(self.error("invalid XML declaration")),
            };
            self.at += 1;
            let value = self.past(
                if quote == '"' { "\"" } else { "'" },
                "the XML declaration does not end",
            )?;
            match name {
                "version" if !version && value == "1.0" => version = true,
                "encoding"
                    if version
                        && !encoding
                        && !standalone
                        && value.eq_ignore_ascii_case("UTF-8") =>
                {
                    encoding = true
                }
                "standalone" if version && !standalone && matches!(value, "yes" | "no") => {
                    standalone = true
                }
                _ => return Err(self.error("invalid XML declaration")),
            }
        }
    }
}

/// The root element of an XML document.
pub fn parse(input: &str) -> Result<Element<'_>, XmlError> {
    parse_with_limits(
        input,
        &Limits {
            elements: MAX_ELEMENTS,
            elements_named: &[],
            attribute_len: |_, _| usize::MAX,
            text_len: |_| usize::MAX,
        },
    )
}

/// Read with format-specific limits, refusing an element or value before retaining it. The
/// existing depth, attribute-count and element-count ceilings still apply.
pub fn parse_with_limits<'a>(input: &'a str, limits: &Limits<'_>) -> Result<Element<'a>, XmlError> {
    parse_with_processing_instructions(input, limits, false)
}

/// Read ADX with bounded, ignored processing instructions.
pub(crate) fn parse_with_processing_instructions<'a>(
    input: &'a str,
    limits: &Limits<'_>,
    allow_pi: bool,
) -> Result<Element<'a>, XmlError> {
    let mut r = Reader { input, at: 0 };
    // Every character first: XML forbids control characters but tab and line ends (found in
    // review: NUL and U+0001 were read).
    if let Some((at, _)) = input.char_indices().find(|(_, c)| !is_xml_char(*c)) {
        r.at = at;
        return Err(r.error("a character XML does not allow"));
    }
    if r.rest().starts_with('\u{feff}') {
        r.at += '\u{feff}'.len_utf8();
    }
    if r.rest().starts_with("<?xml")
        && (!allow_pi || r.rest()[5..].starts_with([' ', '\t', '\r', '\n', '?']))
    {
        r.declaration()?;
    }
    // Open elements, innermost last; the root is taken out when it closes.
    let mut open: Vec<Element> = Vec::new();
    let mut root: Option<Element> = None;
    let mut elements = 0usize;
    let mut named_counts = vec![0usize; limits.elements_named.len()];
    loop {
        // Text up to the next tag: kept only inside an element.
        let text_end = r.rest().find('<').unwrap_or(r.rest().len());
        let text = &r.rest()[..text_end];
        if text.contains("]]>") {
            return Err(r.error("invalid XML character data"));
        }
        if !text.is_empty() {
            match open.last_mut() {
                Some(parent) => {
                    let remaining = (limits.text_len)(parent.name) - parent.text_len;
                    let len = decoded_len(
                        [text].into_iter(),
                        false,
                        remaining,
                        &mut parent.text_after_cr,
                    )
                    .map_err(|problem| {
                        r.error(if problem == "value too long" {
                            "text too long"
                        } else {
                            "an unknown entity or a bare &"
                        })
                    })?;
                    parent.text_len += len;
                    parent.text.push(text);
                }
                None if text.trim_matches([' ', '\t', '\r', '\n']).is_empty() => {}
                None => return Err(r.error("text outside the root element")),
            }
            r.at += text_end;
        }
        if r.at == input.len() {
            break;
        }
        let rest = r.rest();
        if rest.starts_with("<!--") {
            r.at += 4;
            let comment = r.past("-->", "a comment does not end")?;
            if comment.contains("--") || comment.ends_with('-') {
                return Err(r.error("invalid XML comment"));
            }
        } else if rest.starts_with("<!") {
            return Err(r.error("a DTD or CDATA, which TQSL does not write"));
        } else if rest.starts_with("<?") {
            if !allow_pi {
                return Err(r.error("a processing instruction"));
            }
            r.at += 2;
            let target = r.name()?;
            if target.eq_ignore_ascii_case("xml") {
                return Err(r.error("an XML processing instruction"));
            }
            if !r.rest().starts_with("?>") && !r.rest().starts_with([' ', '\t', '\r', '\n']) {
                return Err(r.error("a malformed processing instruction"));
            }
            let body = r.past("?>", "a processing instruction does not end")?;
            if target.len().saturating_add(body.len()) > 64 * 1024 {
                return Err(r.error("a processing instruction is too long"));
            }
            elements += 1;
            if elements > limits.elements.min(MAX_ELEMENTS) {
                return Err(r.error("too many elements"));
            }
        } else if rest.starts_with("</") {
            r.at += 2;
            let name = r.name()?;
            r.skip_space();
            if !r.rest().starts_with('>') {
                return Err(r.error("an end tag does not end"));
            }
            r.at += 1;
            let element = open
                .pop()
                .ok_or_else(|| r.error("an end tag with no start"))?;
            if element.name != name {
                return Err(r.error("an end tag for another element"));
            }
            match open.last_mut() {
                Some(parent) => parent.children.push(element),
                None => root = Some(element),
            }
        } else {
            r.at += 1;
            if root.is_some() {
                return Err(r.error("a second root element"));
            }
            elements += 1;
            if elements > limits.elements.min(MAX_ELEMENTS) {
                return Err(r.error("too many elements"));
            }
            if open.len() == MAX_DEPTH {
                return Err(r.error("elements nested too deep"));
            }
            let mut element = Element {
                name: r.name()?,
                ..Element::default()
            };
            for ((name, max), count) in limits.elements_named.iter().zip(&mut named_counts) {
                if element.name == *name {
                    if *count == *max {
                        return Err(r.error("too many named elements"));
                    }
                    *count += 1;
                }
            }
            loop {
                let before = r.at;
                r.skip_space();
                let rest = r.rest();
                if rest.starts_with("/>") || rest.starts_with('>') {
                    break;
                }
                if r.at == before {
                    return Err(r.error("attributes must be separated by space"));
                }
                if element.attributes.len() == MAX_ATTRIBUTES {
                    return Err(r.error("too many attributes"));
                }
                let name = r.name()?;
                r.skip_space();
                if !r.rest().starts_with('=') {
                    return Err(r.error("an attribute with no value"));
                }
                r.at += 1;
                r.skip_space();
                let quote = match r.rest().chars().next() {
                    Some(q @ ('"' | '\'')) => q,
                    _ => return Err(r.error("an attribute value must be quoted")),
                };
                r.at += 1;
                let value = r.past(
                    if quote == '"' { "\"" } else { "'" },
                    "an attribute value does not end",
                )?;
                if value.contains('<') {
                    return Err(r.error("an attribute value with < or an unknown entity"));
                }
                decoded_len(
                    [value].into_iter(),
                    true,
                    (limits.attribute_len)(element.name, name),
                    &mut false,
                )
                .map_err(|problem| {
                    r.error(if problem == "value too long" {
                        "attribute value too long"
                    } else {
                        "an attribute value with < or an unknown entity"
                    })
                })?;
                if element.attributes.iter().any(|(n, _)| *n == name) {
                    return Err(r.error("an attribute given twice"));
                }
                element.attributes.push((name, value));
            }
            if r.rest().starts_with("/>") {
                r.at += 2;
                match open.last_mut() {
                    Some(parent) => parent.children.push(element),
                    None => root = Some(element),
                }
            } else {
                r.at += 1;
                open.push(element);
            }
        }
    }
    if !open.is_empty() {
        return Err(r.error("an element does not end"));
    }
    root.ok_or_else(|| r.error("no root element"))
}

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

    #[test]
    fn what_tqsl_writes_is_read() {
        let doc = parse(
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<A>\n<!-- a note -->\n<B x=\"1\" y='a &amp; b'>te<!-- c -->xt &lt;&#65;&#x42;</B>\n<C/>\n</A>\n",
        )
        .expect("parses");
        assert_eq!(doc.name, "A");
        assert_eq!(doc.children.len(), 2);
        let b = &doc.children[0];
        assert_eq!(b.attribute("x").as_deref().map(String::as_str), Some("1"));
        assert_eq!(
            b.attribute("y").as_deref().map(String::as_str),
            Some("a & b")
        );
        assert_eq!(b.text().as_str(), "text <AB");
        assert_eq!(doc.children_named("C").count(), 1);
    }

    #[test]
    fn what_could_expand_or_hide_is_refused() {
        for (bad, problem) in [
            (
                "<!DOCTYPE a [<!ENTITY x \"y\">]><a>&x;</a>",
                "a DTD or CDATA, which TQSL does not write",
            ),
            (
                "<a><![CDATA[x]]></a>",
                "a DTD or CDATA, which TQSL does not write",
            ),
            ("<a>&x;</a>", "an unknown entity or a bare &"),
            ("<a>a & b</a>", "an unknown entity or a bare &"),
            (
                "<a b=\"&x;\"/>",
                "an attribute value with < or an unknown entity",
            ),
            ("<a><?pi x?></a>", "a processing instruction"),
            ("<a b=\"1\" b=\"2\"/>", "an attribute given twice"),
            ("<a b=1/>", "an attribute value must be quoted"),
            ("<a></b>", "an end tag for another element"),
            ("<a>", "an element does not end"),
            ("<a/><b/>", "a second root element"),
            ("text<a/>", "text outside the root element"),
            ("<a><!-- open", "a comment does not end"),
            ("", "no root element"),
        ] {
            assert_eq!(
                parse(bad).map(|_| ()).map_err(|e| e.problem),
                Err(problem),
                "{bad}"
            );
        }
    }

    #[test]
    fn limits_are_kept_while_reading() {
        let deep = "<a>".repeat(MAX_DEPTH + 1);
        assert_eq!(
            parse(&deep).err().map(|e| e.problem),
            Some("elements nested too deep")
        );
        let attrs: String = (0..=MAX_ATTRIBUTES)
            .map(|i| format!(" a{i}=\"\""))
            .collect();
        assert_eq!(
            parse(&format!("<a{attrs}/>")).err().map(|e| e.problem),
            Some("too many attributes")
        );
        // Found in review: 128 MiB of < inside a comment made another parser reserve gigabytes; here
        // a comment is skipped, nothing reserved.
        let comment = format!("<a><!--{}--></a>", "<".repeat(1 << 20));
        assert!(parse(&comment).is_ok());
        let many = format!("<a>{}</a>", "<b/>".repeat(MAX_ELEMENTS));
        assert_eq!(
            parse(&many).err().map(|e| e.problem),
            Some("too many elements")
        );
    }

    #[test]
    fn values_are_normalized_as_xml_says() {
        let doc = parse("<a n=\"HOME\tA\" m=\"x\r\ny\" r=\"&#9;\">one\r\ntwo\rthree</a>")
            .expect("parses");
        assert_eq!(
            doc.attribute("n").as_deref().map(String::as_str),
            Some("HOME A")
        );
        assert_eq!(
            doc.attribute("m").as_deref().map(String::as_str),
            Some("x y")
        );
        // A tab written as a reference is kept.
        assert_eq!(
            doc.attribute("r").as_deref().map(String::as_str),
            Some("\t")
        );
        assert_eq!(doc.text().as_str(), "one\ntwo\nthree");
    }

    #[test]
    fn characters_xml_forbids_are_refused() {
        for bad in [
            "<a>\u{1}</a>",
            "<a b=\"\0\"/>",
            "<a>&#1;</a>",
            "<a>&#0;</a>",
            "<a>&#+65;</a>",
            "<a>&#x;</a>",
        ] {
            assert!(parse(bad).is_err(), "{bad:?}");
        }
        assert!(parse("<a>&#65;&#x42;\u{7f}</a>").is_ok());
    }

    #[test]
    fn errors_say_where() {
        let e = parse("<a>\n  <b>&x;</b>\n</a>").expect_err("refused");
        assert_eq!((e.line, e.column), (2, 6));
    }

    #[test]
    fn decoded_text_is_wiped_and_made_at_its_size() {
        fn wiped<T: zeroize::ZeroizeOnDrop>(_: &T) {}
        let doc = parse("<a>abc&amp;def</a>").expect("parses");
        let text = doc.text();
        wiped(&text);
        assert!(text.capacity() >= text.len() && text.capacity() <= "abc&amp;def".len());
    }

    #[test]
    fn bounded_values_stop_before_decoding_an_oversized_value_whole() {
        let limits = Limits {
            elements: 3,
            elements_named: &[("b", 1)],
            attribute_len: |_, _| 4,
            text_len: |_| 4,
        };
        // The invalid entity after the overflow must never be decoded. Both the parser and the
        // allocating decoder stop at the fifth byte; entity encoding does not inflate capacity.
        let oversized = "&#65;".repeat(5) + "&unknown;";
        assert_eq!(
            parse_with_limits(&format!("<a k=\"{oversized}\"/>"), &limits)
                .expect_err("attribute cap")
                .problem,
            "attribute value too long"
        );
        assert_eq!(
            decode_bounded([oversized.as_str()].into_iter(), true, 4),
            Err("value too long")
        );
        assert_eq!(
            parse_with_limits("<a>ab<!-- split -->éx&unknown;</a>", &limits)
                .expect_err("cumulative UTF-8 text cap")
                .problem,
            "text too long"
        );
        let doc = parse_with_limits("<a k=\"&#65;&#66;&#67;&#68;\">ab<!-- -->é</a>", &limits)
            .expect("exact limits fit");
        let value = doc.attribute_bounded("k", 4).expect("fits").expect("k");
        assert_eq!(value.as_str(), "ABCD");
        assert_eq!(value.capacity(), 4);
        assert_eq!(doc.text_bounded(4).expect("fits").as_str(), "abé");
        assert!(doc.attribute_bounded("k", 3).is_err());
        assert!(doc.text_bounded(3).is_err());
        // CRLF normalization still spans a comment boundary.
        assert_eq!(
            parse_with_limits("<a>ab\r<!-- -->\nc</a>", &limits)
                .expect("normalized text fits")
                .text()
                .as_str(),
            "ab\nc"
        );
        assert_eq!(
            parse_with_limits("<a><b/><b invalid", &limits)
                .expect_err("named count before attributes")
                .problem,
            "too many named elements"
        );
        assert_eq!(
            parse_with_limits("<a><b/><c/><d invalid", &limits)
                .expect_err("total count before element")
                .problem,
            "too many elements"
        );
        assert!(parse_with_limits("<a><b/><c/></a>", &limits).is_ok());
    }
}

#[cfg(test)]
mod review_tests {
    use super::parse;

    #[test]
    fn declarations_follow_xml_10_pseudo_attribute_grammar() {
        for declaration in [
            "<?xml nonsense?>",
            "<?xml?>",
            "<?xml version='1.0' nonsense='x'?>",
            "<?xml version='1.0' version='1.0'?>",
            "<?xml encoding='UTF-8' version='1.0'?>",
            "<?xml version='1.0' standalone='yes' encoding='UTF-8'?>",
            "<?xml version='1.0'encoding='UTF-8'?>",
            "<?xml version=1.0?>",
            "<?xml version='1.0' standalone='YES'?>",
            "<?xml version='1.0' encoding='UTF-16'?>",
            "<?xml version='1.&#48;'?>",
            "<?xml version='1.0' encoding='UTF&#45;8'?>",
            "<?xml version='1.0' standalone='y&#101;s'?>",
            "<?xml version='1.1'?>",
            " <?xml version='1.0'?>",
            "<!-- ok --><?xml version='1.0'?>",
        ] {
            assert!(
                parse(&format!("{declaration}<A/>")).is_err(),
                "{declaration}"
            );
        }
        for declaration in [
            "<?xml version='1.0'?>",
            "\u{feff}<?xml\nversion = \"1.0\" encoding='utf-8' standalone = 'no' ?>",
            "<?xml version='1.0' standalone='yes'?>",
        ] {
            assert!(
                parse(&format!("{declaration}<A/>")).is_ok(),
                "{declaration}"
            );
        }
    }

    #[test]
    fn comments_and_character_data_follow_xml_10_grammar() {
        for bad in ["<!-- bad -- comment -->", "<!-- bad --->", "<!-- -- -->"] {
            for input in [
                format!("{bad}<A/>"),
                format!("<A>{bad}</A>"),
                format!("<A/>{bad}"),
            ] {
                assert!(parse(&input).is_err(), "{input}");
            }
        }
        for good in [
            "<!---->",
            "<!---good-->",
            "<!-- good-comment -->",
            "<!-- ]]> -->",
        ] {
            assert!(parse(&format!("<A>{good}</A>")).is_ok(), "{good}");
        }
        assert!(parse("<A>forbidden ]]></A>").is_err());
        assert!(parse("<A>escaped ]]&gt;</A>").is_ok());
        assert!(parse("<A attr=']]>'/>").is_ok());
    }
}