grippo 0.1.1

Parse, match and scrub data at scale.
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
// Project:   grippo
// File:      src/record/xml.rs
// Purpose:   Raw XML bytes as a record: element and attribute paths, a walk and a write-back
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! An XML document's bytes as a [`Record`], read with `xml::Paths`' scanner
//! and no tree.
//!
//! The record has one root member, the root element by its local name. A
//! child step is a local name, `name[n]` the nth child with it from 0, and
//! `name[@attr="v"]` the first whose attribute decodes to `v`. `@name` is an
//! attribute. An element with no child elements is its text, a string, and
//! one with child elements is an object.

use std::borrow::Cow;
use std::ops::Range;

use memchr::memchr3;

use super::{Kind, Miss, Node, Record, Typed, Walk};
use crate::xml::paths::{
    Malformed, Passed, TagPart, attribute_special, close_tag, decode_attribute, decode_text,
    equal_decoded, find_byte, local_name, markup, name_end, pass, prolog, tag_end, tag_part,
};

/// The deepest element [`Record::text`] writes as JSON.
const MAX_JSON_DEPTH: usize = 128;

/// Raw XML bytes, read as a record.
///
/// ```
/// use grippo::record::{Miss, Record, Typed, Xml};
///
/// let xml = Xml::new(br#"<Event><Data Name="User">bob</Data><Data>3</Data></Event>"#);
/// let at = xml.find(&["Event", "Data[1]"])?;
/// assert_eq!(xml.typed(at)?, Typed::Str("3".into()));
/// let at = xml.find(&["Event", r#"Data[@Name="User"]"#])?;
/// assert_eq!(xml.text(at)?, "bob");
/// assert_eq!(xml.find(&["Event", "Data", "@Name", "x"]), Err(Miss::WrongParentType));
/// # Ok::<(), Miss>(())
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Xml<'a> {
    bytes: &'a [u8],
}

/// Where a value sits in an [`Xml`] record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct XmlAt(Place);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Place {
    /// An element: its `<`, and the offset past its start tag.
    Element { lt: usize, content: usize },
    /// An attribute's value, between its quotes.
    Attribute { start: usize, end: usize },
}

/// One step of a path.
enum Step<'k> {
    Attribute(&'k str),
    Child(&'k str, Select<'k>),
}

/// Which of the children with a step's name it takes.
enum Select<'k> {
    Nth(usize),
    /// The first whose attribute, by local name, decodes to the value.
    Where(&'k str, &'k str),
}

/// A value as the record reads it.
enum Value<'a> {
    Text(Cow<'a, str>),
    /// An element with child elements, by its `<`.
    Element(usize),
}

/// How an edit is written over its span.
enum Write {
    /// Escaped for an attribute value in this quote.
    Attribute(u8),
    /// Escaped as element text.
    Text,
    /// A self-closed element's `/>` written as `>`, the text, and a close tag.
    Opened(Range<usize>),
    /// An element with child elements written again from just past its name:
    /// its namespace declarations kept, then the text as its only content.
    Element(Range<usize>),
}

impl<'a> Xml<'a> {
    /// The record in `bytes`.
    #[must_use]
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }

    /// Writes the record to `out` with each value in `edits` replaced by the
    /// bytes given for it, escaped as element text or for the attribute's
    /// quote, invalid UTF-8 and characters XML can't hold as U+FFFD.
    ///
    /// An element with child elements keeps its name and namespace
    /// declarations and loses its other attributes and its children: the
    /// text is its only content. A self-closed element gets a close tag.
    /// Each `At` is from this record, none inside another, in any order.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when an `At` isn't from this record or two
    /// overlap, with `out` left as it was.
    pub fn splice_text<B: AsRef<[u8]>>(
        self,
        edits: &[(XmlAt, B)],
        out: &mut Vec<u8>,
    ) -> Result<(), Miss> {
        let mark = out.len();
        self.splice(edits, out).map_err(|Malformed| {
            out.truncate(mark);
            Miss::Malformed
        })
    }

    fn splice<B: AsRef<[u8]>>(
        self,
        edits: &[(XmlAt, B)],
        out: &mut Vec<u8>,
    ) -> Result<(), Malformed> {
        let doc = self.bytes;
        let mut plans = edits
            .iter()
            .enumerate()
            .map(|(i, (at, _))| self.plan(*at).map(|(span, write)| (span, write, i)))
            .collect::<Result<Vec<(Range<usize>, Write, usize)>, Malformed>>()?;
        plans.sort_unstable_by_key(|(span, _, _)| span.start);
        let mut copied = 0;
        for (span, write, i) in plans {
            if span.start < copied {
                return Err(Malformed);
            }
            out.extend_from_slice(&doc[copied..span.start]);
            let value = edits[i].1.as_ref();
            match write {
                Write::Attribute(quote) => push_escaped(out, value, Some(quote)),
                Write::Text => push_escaped(out, value, None),
                Write::Opened(qname) => {
                    out.push(b'>');
                    push_escaped(out, value, None);
                    push_close(out, &doc[qname]);
                }
                Write::Element(qname) => {
                    let mut at = qname.end;
                    while let TagPart::Attribute(a) = tag_part(doc, &mut at)? {
                        if declaration(&doc[a.name.clone()]) {
                            out.push(b' ');
                            out.extend_from_slice(&doc[a.name.start..=a.value.end]);
                        }
                    }
                    out.push(b'>');
                    push_escaped(out, value, None);
                    push_close(out, &doc[qname]);
                }
            }
            copied = span.end;
        }
        out.extend_from_slice(&doc[copied..]);
        Ok(())
    }

    /// The bytes an edit at `at` replaces, and how it writes them.
    fn plan(self, at: XmlAt) -> Result<(Range<usize>, Write), Malformed> {
        let doc = self.bytes;
        match at.0 {
            Place::Attribute { start, end } => {
                let quote = *doc
                    .get(start.checked_sub(1).ok_or(Malformed)?)
                    .ok_or(Malformed)?;
                let inner = doc.get(start..end).ok_or(Malformed)?;
                let quoted = matches!(quote, b'"' | b'\'') && doc.get(end) == Some(&quote);
                if !quoted || memchr::memchr(quote, inner).is_some() {
                    return Err(Malformed);
                }
                Ok((start..end, Write::Attribute(quote)))
            }
            Place::Element { lt, content } => {
                let qname = self.qname(lt, content)?;
                if self_closed(doc, content) {
                    return Ok((content - 2..content, Write::Opened(qname)));
                }
                let passed = pass(doc, content, Some(&doc[qname.clone()]), true)?;
                if passed.child {
                    Ok((qname.end..passed.after, Write::Element(qname)))
                } else {
                    Ok((content..passed.end, Write::Text))
                }
            }
        }
    }

    /// The name of the element whose `<` is at `lt`, once its tag is checked
    /// to end at `content`.
    fn qname(self, lt: usize, content: usize) -> Result<Range<usize>, Malformed> {
        let doc = self.bytes;
        if doc.get(lt) != Some(&b'<') {
            return Err(Malformed);
        }
        let qname = lt + 1..name_end(doc, lt + 1)?;
        if tag_end(doc, qname.end)?.0 != content {
            return Err(Malformed);
        }
        Ok(qname)
    }

    /// The element whose `<` is at `lt`.
    fn element(self, lt: usize) -> Result<XmlAt, Malformed> {
        let end = name_end(self.bytes, lt + 1)?;
        let (content, _) = tag_end(self.bytes, end)?;
        Ok(XmlAt(Place::Element { lt, content }))
    }

    /// Whether the element at `lt`, the `n`th with its name among its
    /// siblings, is the one `select` takes. `n` counts it.
    fn selects(self, lt: usize, select: &Select<'_>, n: &mut usize) -> Result<bool, Malformed> {
        match select {
            Select::Nth(k) => {
                let hit = *n == *k;
                *n += 1;
                Ok(hit)
            }
            Select::Where(name, value) => self.attribute(lt, name)?.map_or(Ok(false), |range| {
                equal_decoded(&self.bytes[range], value.as_bytes())
            }),
        }
    }

    /// The value of the first attribute of the element at `lt` whose local
    /// name is `name`, namespace declarations aside.
    fn attribute(self, lt: usize, name: &str) -> Result<Option<Range<usize>>, Malformed> {
        let doc = self.bytes;
        let mut at = name_end(doc, lt + 1)?;
        while let TagPart::Attribute(a) = tag_part(doc, &mut at)? {
            let qname = &doc[a.name.clone()];
            if !declaration(qname) && local_name(qname) == name.as_bytes() {
                return Ok(Some(a.value));
            }
        }
        Ok(None)
    }

    /// The child of the element at `lt` that `local` and `select` take.
    fn child(
        self,
        lt: usize,
        content: usize,
        local: &str,
        select: &Select<'_>,
    ) -> Result<XmlAt, Miss> {
        let doc = self.bytes;
        if self_closed(doc, content) {
            return Err(Miss::WrongParentType);
        }
        let name = &doc[lt + 1..name_end(doc, lt + 1).map_err(malformed)?];
        let mut n = 0;
        let mut children = false;
        let mut at = content;
        loop {
            let next = find_byte(doc, at, b'<').map_err(malformed)?;
            match doc.get(next + 1) {
                Some(b'/') => {
                    close_tag(doc, next, name).map_err(malformed)?;
                    // An element with no child element is a string.
                    return Err(if children {
                        Miss::MissingField
                    } else {
                        Miss::WrongParentType
                    });
                }
                Some(b'!' | b'?') => at = markup(doc, next).map_err(malformed)?.0,
                Some(_) => {
                    children = true;
                    let end = name_end(doc, next + 1).map_err(malformed)?;
                    let (inner, closed) = tag_end(doc, end).map_err(malformed)?;
                    if local_name(&doc[next + 1..end]) == local.as_bytes()
                        && self.selects(next, select, &mut n).map_err(malformed)?
                    {
                        return Ok(XmlAt(Place::Element {
                            lt: next,
                            content: inner,
                        }));
                    }
                    at = if closed {
                        inner
                    } else {
                        pass(doc, inner, Some(&doc[next + 1..end]), false)
                            .map_err(malformed)?
                            .after
                    };
                }
                None => return Err(Miss::Malformed),
            }
        }
    }

    /// The value at `at`: an attribute's or a text element's string decoded,
    /// or an element with child elements.
    fn value(self, at: XmlAt) -> Result<Value<'a>, Malformed> {
        let doc = self.bytes;
        match at.0 {
            Place::Attribute { start, end } => {
                attribute_text(doc.get(start..end).ok_or(Malformed)?).map(Value::Text)
            }
            Place::Element { lt, content } => {
                let qname = self.qname(lt, content)?;
                if self_closed(doc, content) {
                    return Ok(Value::Text(Cow::Borrowed("")));
                }
                let Passed { end, child, .. } = pass(doc, content, Some(&doc[qname]), true)?;
                if child {
                    Ok(Value::Element(lt))
                } else {
                    element_text(&doc[content..end]).map(Value::Text)
                }
            }
        }
    }

    /// The element at `lt` as JSON, and the offset past it: attributes as
    /// `@name`, child elements by local name, a repeated name as a list, and
    /// text as a string, or as `#text` beside attributes when it isn't empty.
    /// Text beside child elements is left out.
    fn json(self, lt: usize, depth: usize) -> Result<(serde_json::Value, usize), Malformed> {
        use serde_json::{Map, Value as Json};

        if depth > MAX_JSON_DEPTH {
            return Err(Malformed);
        }
        let doc = self.bytes;
        let qname = lt + 1..name_end(doc, lt + 1)?;
        let mut map = Map::new();
        let mut at = qname.end;
        let (content, closed) = loop {
            match tag_part(doc, &mut at)? {
                TagPart::Attribute(a) => {
                    let name = &doc[a.name.clone()];
                    if !declaration(name) {
                        let key = format!("@{}", utf8(local_name(name))?);
                        let text = attribute_text(&doc[a.value])?;
                        map.insert(key, Json::String(text.into_owned()));
                    }
                }
                TagPart::End { after, closed } => break (after, closed),
            }
        };
        let leaf = |mut map: Map<String, Json>, text: Cow<'_, str>| {
            if map.is_empty() {
                return Json::String(text.into_owned());
            }
            if !text.is_empty() {
                map.insert("#text".to_owned(), Json::String(text.into_owned()));
            }
            Json::Object(map)
        };
        if closed {
            return Ok((leaf(map, Cow::Borrowed("")), content));
        }
        let mut children = false;
        let mut at = content;
        loop {
            let next = find_byte(doc, at, b'<')?;
            match doc.get(next + 1) {
                Some(b'/') => {
                    let after = close_tag(doc, next, &doc[qname])?;
                    let value = if children {
                        Json::Object(map)
                    } else {
                        leaf(map, element_text(&doc[content..next])?)
                    };
                    return Ok((value, after));
                }
                Some(b'!' | b'?') => at = markup(doc, next)?.0,
                Some(_) => {
                    children = true;
                    let end = name_end(doc, next + 1)?;
                    let key = utf8(local_name(&doc[next + 1..end]))?.to_owned();
                    let (value, after) = self.json(next, depth + 1)?;
                    match map.get_mut(&key) {
                        Some(Json::Array(list)) => list.push(value),
                        Some(first) => {
                            let first = std::mem::take(first);
                            map.insert(key, Json::Array(vec![first, value]));
                        }
                        None => {
                            map.insert(key, value);
                        }
                    }
                    at = after;
                }
                None => return Err(Malformed),
            }
        }
    }
}

impl<'a> Record<'a> for Xml<'a> {
    /// An element or an attribute value, by its offsets in the document.
    type At = XmlAt;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<XmlAt, Miss> {
        let Some((first, rest)) = path.split_first() else {
            return Err(Miss::MissingRoot);
        };
        let lt = prolog(self.bytes).map_err(malformed)?;
        let root = self.element(lt).map_err(malformed)?;
        let Step::Child(local, select) = step(first.as_ref()) else {
            return Err(Miss::MissingRoot);
        };
        let name = &self.bytes[lt + 1..name_end(self.bytes, lt + 1).map_err(malformed)?];
        if local_name(name) != local.as_bytes()
            || !self.selects(lt, &select, &mut 0).map_err(malformed)?
        {
            return Err(Miss::MissingRoot);
        }
        self.find_below(root, rest)
    }

    fn find_below<K: AsRef<str>>(self, mut at: XmlAt, path: &[K]) -> Result<XmlAt, Miss> {
        for key in path {
            let Place::Element { lt, content } = at.0 else {
                return Err(Miss::WrongParentType);
            };
            at = match step(key.as_ref()) {
                Step::Attribute(name) => {
                    if self.qname(lt, content).is_err() {
                        return Err(Miss::Malformed);
                    }
                    let range = self.attribute(lt, name).map_err(malformed)?;
                    let range = range.ok_or(Miss::MissingField)?;
                    XmlAt(Place::Attribute {
                        start: range.start,
                        end: range.end,
                    })
                }
                Step::Child(local, select) => self.child(lt, content, local, &select)?,
            };
        }
        Ok(at)
    }

    fn typed(self, at: XmlAt) -> Result<Typed<'a>, Miss> {
        match self.value(at).map_err(malformed)? {
            Value::Text(text) => Ok(Typed::Str(text)),
            Value::Element(..) => Ok(Typed::Map),
        }
    }

    fn text(self, at: XmlAt) -> Result<Cow<'a, str>, Miss> {
        match self.value(at).map_err(malformed)? {
            Value::Text(text) => Ok(text),
            Value::Element(lt) => {
                let (json, _) = self.json(lt, 0).map_err(malformed)?;
                Ok(Cow::Owned(json.to_string()))
            }
        }
    }
}

impl<'a> Walk<'a> for Xml<'a> {
    /// Each element, then its attributes as `@name` one level below it, then
    /// its child elements. An element with child elements is a
    /// [`Kind::Map`] and any other a [`Kind::Str`], its attributes below it
    /// either way. A repeated name is keyed by its local name each time.
    fn walk<F: FnMut(Node<'a, XmlAt>)>(self, mut visit: F) -> Result<(), Miss> {
        let text = std::str::from_utf8(self.bytes).map_err(|_| Miss::Malformed)?;
        let mut parents = Vec::new();
        scan(text, &mut parents, None::<&mut F>).map_err(malformed)?;
        scan(text, &mut parents, Some(&mut visit)).map_err(malformed)
    }
}

/// One pass over the document `text`. The first, with no `visit`, checks it
/// and records, for each element in the order they open, whether it has a
/// child element. The second calls `visit`, each element's kind known when it
/// opens.
fn scan<'a, F: FnMut(Node<'a, XmlAt>)>(
    text: &'a str,
    parents: &mut Vec<bool>,
    mut visit: Option<&mut F>,
) -> Result<(), Malformed> {
    let doc = text.as_bytes();
    // Each open element: its name, and its slot in `parents`.
    let mut open: Vec<(Range<usize>, usize)> = Vec::new();
    let mut names: Vec<Range<usize>> = Vec::new();
    let mut opened = 0;
    let mut at = prolog(doc)?;
    loop {
        let lt = at;
        let qname = lt + 1..name_end(doc, lt + 1)?;
        let slot = opened;
        opened += 1;
        let mut part = qname.end;
        let (content, closed) = loop {
            match tag_part(doc, &mut part)? {
                TagPart::Attribute(a) if visit.is_none() => {
                    let name = &doc[a.name.clone()];
                    let seen = names.iter().any(|n| &doc[n.clone()] == name);
                    if seen || decode_attribute(&doc[a.value], |_| {}).is_err() {
                        return Err(Malformed);
                    }
                    names.push(a.name);
                }
                TagPart::Attribute(_) => {}
                TagPart::End { after, closed } => break (after, closed),
            }
        };
        names.clear();
        match visit.as_deref_mut() {
            None => {
                if let Some(&(_, parent)) = open.last() {
                    parents[parent] = true;
                }
                parents.push(false);
            }
            Some(visit) => {
                let depth = open.len();
                let kind = if *parents.get(slot).ok_or(Malformed)? {
                    Kind::Map
                } else {
                    Kind::Str
                };
                visit(Node {
                    depth,
                    key: Some(Cow::Borrowed(local(text, qname.clone()))),
                    kind,
                    at: XmlAt(Place::Element { lt, content }),
                });
                let mut part = qname.end;
                while let TagPart::Attribute(a) = tag_part(doc, &mut part)? {
                    if declaration(&doc[a.name.clone()]) {
                        continue;
                    }
                    visit(Node {
                        depth: depth + 1,
                        key: Some(Cow::Owned(format!("@{}", local(text, a.name)))),
                        kind: Kind::Str,
                        at: XmlAt(Place::Attribute {
                            start: a.value.start,
                            end: a.value.end,
                        }),
                    });
                }
            }
        }
        if !closed {
            open.push((qname, slot));
        }
        at = content;
        // Content up to the next element's start, closing elements on the way.
        loop {
            let Some((qname, _)) = open.last() else {
                return epilogue(doc, at);
            };
            let next = find_byte(doc, at, b'<')?;
            if visit.is_none() {
                decode_text(&doc[at..next], |_| {})?;
            }
            match doc.get(next + 1) {
                Some(b'/') => {
                    at = close_tag(doc, next, &doc[qname.clone()])?;
                    open.pop();
                }
                Some(b'!' | b'?') => at = markup(doc, next)?.0,
                Some(_) => {
                    at = next;
                    break;
                }
                None => return Err(Malformed),
            }
        }
    }
}

/// Checks that only whitespace, comments and processing instructions follow
/// the root element.
fn epilogue(doc: &[u8], mut at: usize) -> Result<(), Malformed> {
    loop {
        while let Some(b' ' | b'\t' | b'\n' | b'\r') = doc.get(at) {
            at += 1;
        }
        if at == doc.len() {
            return Ok(());
        }
        let rest = &doc[at..];
        if !(rest.starts_with(b"<?") || rest.starts_with(b"<!--")) {
            return Err(Malformed);
        }
        at = markup(doc, at)?.0;
    }
}

/// A path key as a step. A key whose brackets don't read is never an XML
/// name, so it matches nothing.
fn step(key: &str) -> Step<'_> {
    if let Some(name) = key.strip_prefix('@') {
        return Step::Attribute(name);
    }
    let (name, select) = key
        .strip_suffix(']')
        .and_then(|k| k.split_once('['))
        .filter(|(name, _)| !name.is_empty())
        .and_then(|(name, inside)| select(inside).map(|select| (name, select)))
        .unwrap_or((key, Select::Nth(0)));
    Step::Child(name, select)
}

/// The inside of a step's brackets: `n`, or `@attr="v"` in either quote.
fn select(inside: &str) -> Option<Select<'_>> {
    if let Some(predicate) = inside.strip_prefix('@') {
        let (attribute, value) = predicate.split_once('=')?;
        let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
        let value = value.strip_prefix(quote)?.strip_suffix(quote)?;
        let plain = !attribute.is_empty() && !value.contains(quote);
        return plain.then_some(Select::Where(attribute, value));
    }
    let digits = !inside.is_empty()
        && inside.bytes().all(|b| b.is_ascii_digit())
        && (inside == "0" || !inside.starts_with('0'));
    digits
        .then(|| inside.parse().ok())
        .flatten()
        .map(Select::Nth)
}

/// Whether a self-closed tag ends just before `content`.
fn self_closed(doc: &[u8], content: usize) -> bool {
    content >= 2 && doc.get(content - 2) == Some(&b'/')
}

/// Whether an attribute's qualified name is a namespace declaration.
fn declaration(qname: &[u8]) -> bool {
    qname == b"xmlns" || qname.starts_with(b"xmlns:")
}

/// The local part of the name at `range` in `text`.
fn local(text: &str, range: Range<usize>) -> &str {
    let name = &text[range];
    name.split_once(':').map_or(name, |(_, local)| local)
}

fn utf8(bytes: &[u8]) -> Result<&str, Malformed> {
    std::str::from_utf8(bytes).map_err(|_| Malformed)
}

const fn malformed(_: Malformed) -> Miss {
    Miss::Malformed
}

/// An element's content with no child elements, decoded, borrowed when it
/// holds no entity, markup or carriage return.
fn element_text(raw: &[u8]) -> Result<Cow<'_, str>, Malformed> {
    if memchr3(b'&', b'<', b'\r', raw).is_none() {
        return utf8(raw).map(Cow::Borrowed);
    }
    let mut out = Vec::with_capacity(raw.len());
    decode_text(raw, |part| out.extend_from_slice(part))?;
    String::from_utf8(out)
        .map(Cow::Owned)
        .map_err(|_| Malformed)
}

/// An attribute value decoded, borrowed when it needs no decoding.
fn attribute_text(raw: &[u8]) -> Result<Cow<'_, str>, Malformed> {
    if !raw.iter().any(|&b| attribute_special(b)) {
        return utf8(raw).map(Cow::Borrowed);
    }
    let mut out = Vec::with_capacity(raw.len());
    decode_attribute(raw, |part| out.extend_from_slice(part))?;
    String::from_utf8(out)
        .map(Cow::Owned)
        .map_err(|_| Malformed)
}

/// Appends `</qname>`.
fn push_close(out: &mut Vec<u8>, qname: &[u8]) {
    out.extend_from_slice(b"</");
    out.extend_from_slice(qname);
    out.push(b'>');
}

/// Appends `value` escaped as element text, or as an attribute value in
/// `quote`, so it reads back as it is: invalid UTF-8 and characters XML can't
/// hold as U+FFFD.
fn push_escaped(out: &mut Vec<u8>, value: &[u8], quote: Option<u8>) {
    for c in String::from_utf8_lossy(value).chars() {
        let entity: Option<&[u8]> = match c {
            '&' => Some(b"&amp;"),
            '<' => Some(b"&lt;"),
            '>' if quote.is_none() => Some(b"&gt;"),
            '"' if quote == Some(b'"') => Some(b"&quot;"),
            '\'' if quote == Some(b'\'') => Some(b"&apos;"),
            // Read back, a raw CR is a line end, and a tab or LF in an
            // attribute a space.
            '\r' => Some(b"&#13;"),
            '\t' if quote.is_some() => Some(b"&#9;"),
            '\n' if quote.is_some() => Some(b"&#10;"),
            '\t' | '\n' => None,
            c if c < ' ' || matches!(c, '\u{FFFE}' | '\u{FFFF}') => Some("\u{FFFD}".as_bytes()),
            _ => None,
        };
        match entity {
            Some(entity) => out.extend_from_slice(entity),
            None => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()),
        }
    }
}

#[cfg(test)]
mod tests;