grippo 0.1.2

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
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
// Project:   grippo
// File:      src/xml/paths.rs
// Purpose:   Many XML paths read from a raw document in one pass, with no tree and no event stream
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Many paths read from a raw XML document in one pass.
//!
//! [`Paths`] compiles a set of [`Path`]s into a tree of wanted elements. A
//! read walks the document once: each element on a wanted path has its
//! children's names looked up in that tree, every other element is skipped by
//! counting its tags with no name, attribute or text read, and the walk stops
//! once every path has its answer. Each path gets a [`Slot`]: the value's raw
//! bytes and its [`Kind`], or why there's none.
//!
//! ```
//! use grippo::xml::{Kind, Path, Paths, Slot, Slots};
//!
//! let paths = Paths::new([
//!     Path::parse("Event.System.EventID")?,
//!     Path::parse("Event.System.Provider@Name")?,
//!     Path::parse(r#"Event.EventData.Data[@Name="TargetUserName"]"#)?,
//!     Path::parse("Event.EventData.Data[1]")?,
//!     Path::parse("Event.System.EventID.Value")?,
//! ]);
//! let mut slots = Slots::new();
//! let doc = br#"<Event xmlns="urn:example:event"><System><Provider Name="Security"/><EventID>4624</EventID></System><EventData><Data Name="SubjectUserName">svc</Data><Data Name="TargetUserName">a &amp; b</Data></EventData></Event>"#;
//! let values = paths.read(doc, &mut slots);
//!
//! let id = values.get(0).and_then(Slot::found);
//! assert_eq!(id.map(|v| (v.text(), v.kind())), Some(("4624", Kind::Text)));
//! let provider = values.get(1).and_then(Slot::found).and_then(|v| v.to_str());
//! assert_eq!(provider.as_deref(), Some("Security"));
//! let user = values.get(2).and_then(Slot::found).and_then(|v| v.to_str());
//! assert_eq!(user.as_deref(), Some("a & b"));
//! assert_eq!(values.get(3).and_then(Slot::found).map(|v| v.text()), Some("a &amp; b"));
//! assert_eq!(values.get(4), Some(Slot::WrongParentType(3)));
//! # Ok::<(), grippo::xml::PathError>(())
//! ```

use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::str::FromStr;

use memchr::{memchr, memchr2, memchr3, memmem};
use thiserror::Error;

/// The namespace the `xml` prefix is always bound to.
const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";

/// One path into an XML document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Path {
    steps: Vec<Step>,
    /// An attribute of the last element, when the path ends in one.
    attribute: Option<Name>,
}

/// An element or attribute name: its local name, and the namespace URI it
/// must be in when the path gave it a prefix.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Name {
    local: Box<str>,
    namespace: Option<Box<str>>,
}

/// Which of the children with a step's name the step takes.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Select {
    /// The nth, from 0.
    Nth(usize),
    /// The first whose attribute has this value.
    Attribute(Name, Box<str>),
}

/// One element step down a path.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Step {
    name: Name,
    select: Select,
}

/// Why a path can't be built.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PathError {
    /// A path with no steps.
    #[error("a path needs at least one element")]
    Empty,
    /// Path text that isn't a path.
    #[error("{why} at byte {at}")]
    Syntax {
        /// The byte offset where reading stopped.
        at: usize,
        /// What was expected there.
        why: &'static str,
    },
    /// A prefix with no namespace bound to it.
    #[error("the prefix {prefix:?} has no namespace bound to it")]
    UnboundPrefix {
        /// The prefix.
        prefix: String,
    },
}

impl Path {
    /// A path in text, read with no prefixes bound but `xml`.
    ///
    /// # Errors
    ///
    /// As [`Path::parse_with`].
    pub fn parse(text: &str) -> Result<Self, PathError> {
        Self::parse_with(text, &[])
    }

    /// A path in text, its prefixes read through `prefixes`, each a prefix
    /// and the namespace URI bound to it.
    ///
    /// - `a.b.c` steps through three elements, each the first child of its
    ///   parent with that name.
    /// - `a.b@id` is the attribute `id` of `b`.
    /// - `a.b[2]` is the third `b`, counted from 0 as `json::Path` counts.
    /// - `a.b[@Name="x"]` is the first `b` whose attribute `Name` is `x`,
    ///   written in `"` or `'` with no escapes.
    /// - A name with no prefix matches the local name in any namespace. `e:b`
    ///   matches `b` only in the namespace bound to `e`. `xml` is always bound.
    ///
    /// A name can't hold `.`, `[`, `]`, `@`, `=`, a quote or whitespace.
    ///
    /// # Errors
    ///
    /// [`PathError::Empty`] for empty text, [`PathError::Syntax`] for an empty
    /// name, a bracket holding neither an index nor a predicate, or text after
    /// the attribute, and [`PathError::UnboundPrefix`] for a prefix not in
    /// `prefixes`.
    pub fn parse_with(text: &str, prefixes: &[(&str, &str)]) -> Result<Self, PathError> {
        if text.is_empty() {
            return Err(PathError::Empty);
        }
        let mut reader = PathReader {
            text,
            at: 0,
            prefixes,
        };
        let mut steps = Vec::new();
        loop {
            let name = reader.name()?;
            let select = if reader.eat(b'[') {
                reader.select()?
            } else {
                Select::Nth(0)
            };
            steps.push(Step { name, select });
            match reader.peek() {
                None => {
                    return Ok(Self {
                        steps,
                        attribute: None,
                    });
                }
                Some(b'.') => reader.at += 1,
                Some(b'@') => {
                    reader.at += 1;
                    let attribute = Some(reader.name()?);
                    if reader.peek().is_some() {
                        return Err(syntax(reader.at, "the end of the path after an attribute"));
                    }
                    return Ok(Self { steps, attribute });
                }
                Some(_) => return Err(syntax(reader.at, "`.`, `[` or `@` after a name")),
            }
        }
    }
}

impl FromStr for Path {
    type Err = PathError;

    fn from_str(text: &str) -> Result<Self, PathError> {
        Self::parse(text)
    }
}

const fn syntax(at: usize, why: &'static str) -> PathError {
    PathError::Syntax { at, why }
}

/// Path text as it's read.
struct PathReader<'t, 'p> {
    text: &'t str,
    at: usize,
    prefixes: &'p [(&'p str, &'p str)],
}

impl<'t> PathReader<'t, '_> {
    fn peek(&self) -> Option<u8> {
        self.text.as_bytes().get(self.at).copied()
    }

    fn eat(&mut self, byte: u8) -> bool {
        let hit = self.peek() == Some(byte);
        self.at += usize::from(hit);
        hit
    }

    fn run(&mut self) -> &'t str {
        let start = self.at;
        let len = self.text.as_bytes()[start..]
            .iter()
            .position(|&b| !path_name_byte(b))
            .unwrap_or(self.text.len() - start);
        self.at += len;
        &self.text[start..start + len]
    }

    /// A name, its prefix resolved.
    fn name(&mut self) -> Result<Name, PathError> {
        let first = self.run().to_owned();
        if first.is_empty() {
            return Err(syntax(self.at, "a name"));
        }
        if !self.eat(b':') {
            return Ok(Name {
                local: first.into_boxed_str(),
                namespace: None,
            });
        }
        let local = self.run();
        if local.is_empty() {
            return Err(syntax(self.at, "a local name after `:`"));
        }
        let namespace = if first == "xml" {
            XML_NAMESPACE
        } else {
            self.prefixes
                .iter()
                .find(|(prefix, _)| *prefix == first)
                .map(|(_, uri)| *uri)
                .ok_or(PathError::UnboundPrefix { prefix: first })?
        };
        Ok(Name {
            local: local.into(),
            namespace: Some(namespace.into()),
        })
    }

    /// The inside of a `[...]`, from just past the `[` to just past the `]`.
    fn select(&mut self) -> Result<Select, PathError> {
        let select = if self.eat(b'@') {
            let name = self.name()?;
            if !self.eat(b'=') {
                return Err(syntax(self.at, "`=` after the attribute"));
            }
            let quote = self
                .peek()
                .filter(|&b| b == b'"' || b == b'\'')
                .ok_or_else(|| syntax(self.at, "a quoted value"))?;
            let from = self.at + 1;
            let len = memchr(quote, &self.text.as_bytes()[from..])
                .ok_or_else(|| syntax(self.at, "a closing quote"))?;
            self.at = from + len + 1;
            Select::Attribute(name, self.text[from..from + len].into())
        } else {
            let from = self.at;
            let digits = self.text.as_bytes()[from..]
                .iter()
                .take_while(|b| b.is_ascii_digit())
                .count();
            let text = &self.text[from..from + digits];
            if text.len() > 1 && text.starts_with('0') {
                return Err(syntax(from, "an index with no leading zero"));
            }
            let index = text
                .parse::<usize>()
                .map_err(|_| syntax(from, "an index or `@`"))?;
            self.at += digits;
            Select::Nth(index)
        };
        if !self.eat(b']') {
            return Err(syntax(self.at, "`]`"));
        }
        Ok(select)
    }
}

/// Whether `b` can be part of a name in path text.
const fn path_name_byte(b: u8) -> bool {
    !matches!(
        b,
        b'.' | b'[' | b']' | b'@' | b'=' | b':' | b'"' | b'\'' | b' ' | b'\t' | b'\n' | b'\r'
    )
}

/// What a found value holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
    /// An element with no child elements and text that isn't all whitespace,
    /// or any attribute.
    Text,
    /// An element with at least one child element.
    Element,
    /// An element with no child elements and no text but whitespace.
    Empty,
}

/// Where a found value sits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Source {
    /// Between an element's tags.
    Content,
    /// Between an attribute's quotes.
    Attribute,
}

/// A value found in the document: its raw bytes and what it holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Raw<'a> {
    text: &'a str,
    kind: Kind,
    /// The value's first byte in the document.
    start: usize,
    source: Source,
}

impl<'a> Raw<'a> {
    /// The value's offsets in the document it was read from.
    #[must_use]
    pub const fn span(self) -> Range<usize> {
        self.start..self.start + self.text.len()
    }

    /// The value as the document spells it, entities still encoded: an
    /// element's content between its tags, comments, CDATA and child elements
    /// included, or an attribute's value between its quotes.
    #[must_use]
    pub const fn text(self) -> &'a str {
        self.text
    }

    /// What the value holds.
    #[must_use]
    pub const fn kind(self) -> Kind {
        self.kind
    }

    /// Whether the value is an attribute's.
    #[must_use]
    pub const fn is_attribute(self) -> bool {
        matches!(self.source, Source::Attribute)
    }

    /// The value as a string, borrowed when it needs no decoding: entities
    /// decoded, line ends read as `\n`, and an element's CDATA kept and its
    /// comments and processing instructions dropped. An attribute's tabs and
    /// line ends read as spaces. `None` for an element with child elements.
    #[must_use]
    pub fn to_str(self) -> Option<Cow<'a, str>> {
        let bytes = self.text.as_bytes();
        let plain = match self.source {
            Source::Content if self.kind == Kind::Element => return None,
            Source::Content => memchr3(b'&', b'<', b'\r', bytes).is_none(),
            Source::Attribute => !bytes.iter().any(|&b| attribute_special(b)),
        };
        if plain {
            return Some(Cow::Borrowed(self.text));
        }
        let mut out = Vec::with_capacity(bytes.len());
        let decoded = match self.source {
            Source::Content => decode_text(bytes, |part| out.extend_from_slice(part)),
            Source::Attribute => decode_attribute(bytes, |part| out.extend_from_slice(part)),
        };
        decoded.ok()?;
        String::from_utf8(out).ok().map(Cow::Owned)
    }
}

/// What the document holds at one path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Slot<'a> {
    /// The value at the path.
    Found(Raw<'a>),
    /// The root element isn't the path's first step.
    MissingRoot,
    /// The element or attribute at this index of the path isn't in its
    /// parent. The attribute's index is the number of element steps.
    MissingField(usize),
    /// The element that should hold the step at this index of the path is
    /// text, with no child elements.
    WrongParentType(usize),
    /// The document is malformed where the path was read.
    Malformed,
}

impl<'a> Slot<'a> {
    /// The value, when one was found.
    #[must_use]
    pub const fn found(self) -> Option<Raw<'a>> {
        match self {
            Self::Found(raw) => Some(raw),
            _ => None,
        }
    }
}

/// A compiled set of paths, read together from each document. `Send + Sync`,
/// so one set serves every worker.
#[derive(Debug, Clone)]
pub struct Paths {
    /// Node 0 is the document. Every other node is an element step below its
    /// parent.
    nodes: Vec<Node>,
    /// Each node's children grouped by name, sorted by local name.
    groups: Vec<Group>,
    selects: Vec<Selector>,
    /// Each node's wanted attributes.
    attributes: Vec<Name>,
    plans: Vec<Plan>,
    /// Some name in the set has a namespace, so the walk tracks bindings.
    namespaced: bool,
}

#[derive(Debug, Clone)]
struct Node {
    groups: Range<usize>,
    selects: Range<usize>,
    attributes: Range<usize>,
    /// A path ends at this element, so its content and kind are wanted.
    leaf: bool,
    /// Answers below and at this node a read still owes: one for finding
    /// the node, one for its content when it's a leaf, one per attribute.
    pending: usize,
}

/// A node's children with one name.
#[derive(Debug, Clone)]
struct Group {
    local: Box<str>,
    namespace: Option<Box<str>>,
    selects: Range<usize>,
    /// Matching a child needs its attributes read.
    attributes: bool,
}

#[derive(Debug, Clone)]
struct Selector {
    select: Select,
    node: usize,
}

#[derive(Debug, Clone)]
struct Plan {
    /// The nodes from the root element down.
    chain: Box<[usize]>,
    /// The wanted attribute, as an index into [`Paths::attributes`].
    attribute: Option<usize>,
}

impl Paths {
    /// Compiles `paths`, one slot each in the order given.
    #[must_use]
    pub fn new<I: IntoIterator<Item = Path>>(paths: I) -> Self {
        let mut tree = Tree::default();
        let plans: Vec<(Vec<usize>, Option<(usize, usize)>)> =
            paths.into_iter().map(|path| tree.insert(path)).collect();
        tree.finish(plans)
    }

    /// The number of paths.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.plans.len()
    }

    /// Whether the set has no paths.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.plans.is_empty()
    }

    /// Reads every path from the document `xml` in one pass, into `slots`.
    ///
    /// `slots` is scratch reused from one document to the next, so a read
    /// allocates nothing once it has grown to this set's size. The document
    /// is read only as far as the last answer, and its bytes are checked as
    /// [`Values::get`] says.
    pub fn read<'s, 'a>(&'s self, xml: &'a [u8], slots: &'s mut Slots) -> Values<'s, 'a> {
        let Slots {
            visits,
            attributes,
            counts,
            scope,
            tag,
        } = slots;
        visits.clear();
        visits.resize(self.nodes.len(), Visit::default());
        attributes.clear();
        attributes.resize(self.attributes.len(), Found::default());
        counts.clear();
        counts.resize(self.groups.len(), 0);
        scope.clear();
        if !self.plans.is_empty() {
            // A malformed document keeps what was read before the fault.
            let _ = Walk {
                paths: self,
                doc: xml,
                visits: visits.as_mut_slice(),
                attributes: attributes.as_mut_slice(),
                counts: counts.as_mut_slice(),
                scope,
                tag,
                left: self.nodes[0].pending,
            }
            .document();
        }
        Values {
            paths: self,
            visits: visits.as_slice(),
            attributes: attributes.as_slice(),
            doc: xml,
        }
    }

    /// The groups of `node` whose local name is `local`.
    fn groups_of(&self, node: usize, local: &[u8]) -> Range<usize> {
        let Range { start, end } = self.nodes[node].groups;
        let groups = &self.groups[start..end];
        let from = groups.partition_point(|g| g.local.as_bytes() < local);
        let len = groups[from..]
            .iter()
            .take_while(|g| g.local.as_bytes() == local)
            .count();
        start + from..start + from + len
    }
}

/// The node tree as it's built.
struct Tree {
    children: Vec<Vec<(Name, Select, usize)>>,
    attributes: Vec<Vec<Name>>,
    leaf: Vec<bool>,
    index: HashMap<(usize, Name, Select), usize>,
}

impl Default for Tree {
    fn default() -> Self {
        Self {
            children: vec![Vec::new()],
            attributes: vec![Vec::new()],
            leaf: vec![false],
            index: HashMap::new(),
        }
    }
}

impl Tree {
    /// The chain of nodes `path` goes through, adding the ones that are new,
    /// and its attribute as a node and an index among that node's.
    fn insert(&mut self, path: Path) -> (Vec<usize>, Option<(usize, usize)>) {
        let mut at = 0;
        let mut chain = Vec::with_capacity(path.steps.len());
        for Step { name, select } in path.steps {
            let next = self.children.len();
            let node = *self
                .index
                .entry((at, name.clone(), select.clone()))
                .or_insert(next);
            if node == next {
                self.children.push(Vec::new());
                self.attributes.push(Vec::new());
                self.leaf.push(false);
                self.children[at].push((name, select, next));
            }
            chain.push(node);
            at = node;
        }
        let attribute = match path.attribute {
            None => {
                self.leaf[at] = true;
                None
            }
            Some(name) => {
                let wanted = &mut self.attributes[at];
                let i = wanted.iter().position(|n| *n == name).unwrap_or_else(|| {
                    wanted.push(name);
                    wanted.len() - 1
                });
                Some((at, i))
            }
        };
        (chain, attribute)
    }

    fn finish(self, plans: Vec<(Vec<usize>, Option<(usize, usize)>)>) -> Paths {
        let count = self.children.len();
        let mut nodes = Vec::with_capacity(count);
        let mut groups: Vec<Group> = Vec::new();
        let mut selects = Vec::new();
        let mut attributes = Vec::new();
        let mut namespaced = false;
        for ((mut children, wanted), leaf) in self
            .children
            .into_iter()
            .zip(self.attributes)
            .zip(self.leaf)
        {
            children.sort_unstable();
            let first_group = groups.len();
            let first_select = selects.len();
            for (name, select, node) in children {
                namespaced |= name.namespace.is_some();
                if let Select::Attribute(attribute, _) = &select {
                    namespaced |= attribute.namespace.is_some();
                }
                let fresh = groups.len() == first_group
                    || groups.last().is_some_and(|g: &Group| {
                        *g.local != *name.local || g.namespace != name.namespace
                    });
                if fresh {
                    groups.push(Group {
                        attributes: name.namespace.is_some(),
                        local: name.local,
                        namespace: name.namespace,
                        selects: selects.len()..selects.len(),
                    });
                }
                if let Some(group) = groups.last_mut() {
                    group.attributes |= matches!(select, Select::Attribute(..));
                    group.selects.end += 1;
                }
                selects.push(Selector { select, node });
            }
            let first_attribute = attributes.len();
            namespaced |= wanted.iter().any(|n| n.namespace.is_some());
            attributes.extend(wanted);
            nodes.push(Node {
                groups: first_group..groups.len(),
                selects: first_select..selects.len(),
                attributes: first_attribute..attributes.len(),
                leaf,
                pending: 0,
            });
        }
        // A child's id is always past its parent's, so children are summed first.
        for n in (0..count).rev() {
            let below: usize = selects[nodes[n].selects.clone()]
                .iter()
                .map(|s: &Selector| nodes[s.node].pending)
                .sum();
            let node = &mut nodes[n];
            node.pending =
                usize::from(n != 0) + usize::from(node.leaf) + node.attributes.len() + below;
        }
        let plans = plans
            .into_iter()
            .map(|(chain, attribute)| Plan {
                chain: chain.into_boxed_slice(),
                attribute: attribute.map(|(node, i)| nodes[node].attributes.start + i),
            })
            .collect();
        Paths {
            nodes,
            groups,
            selects,
            attributes,
            plans,
            namespaced,
        }
    }
}

/// Scratch for [`Paths::read`], reused from one document to the next. One
/// `Slots` serves any set, and grows to the largest it has read.
#[derive(Debug, Clone, Default)]
pub struct Slots {
    visits: Vec<Visit>,
    attributes: Vec<Found>,
    /// Children of each group's name seen so far in the element being walked.
    counts: Vec<usize>,
    /// Namespace bindings in scope on the walked path.
    scope: Vec<Binding>,
    /// The attributes of the tag last read.
    tag: Vec<Attribute>,
}

impl Slots {
    /// Empty scratch. The first read sizes it.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            visits: Vec::new(),
            attributes: Vec::new(),
            counts: Vec::new(),
            scope: Vec::new(),
            tag: Vec::new(),
        }
    }
}

/// What a read found at one node.
#[derive(Debug, Clone, Copy, Default)]
struct Visit {
    /// One past the `<` of the element the node matched, 0 until one does.
    tag: usize,
    /// The content's offsets.
    start: usize,
    end: usize,
    /// Set once the walk passes the element's close, or for the document
    /// once its root element's tag is read.
    closed: bool,
    kind: Option<Kind>,
}

/// What a read found for one wanted attribute.
#[derive(Debug, Clone, Default)]
struct Found {
    /// The element's tag was read.
    read: bool,
    value: Option<Range<usize>>,
}

/// The `<` of the root element, past a byte order mark, the XML declaration,
/// comments, processing instructions and whitespace.
pub fn prolog(doc: &[u8]) -> Result<usize, Malformed> {
    let mut at = if doc.starts_with(b"\xEF\xBB\xBF") {
        3
    } else {
        0
    };
    loop {
        at = space(doc, at);
        if doc.get(at) != Some(&b'<') {
            return Err(Malformed);
        }
        match doc.get(at + 1) {
            Some(b'?') => at = find(doc, at + 2, b"?>")? + 2,
            // A DOCTYPE is refused, so no entity it declares is ever read.
            Some(b'!') if doc[at..].starts_with(b"<!--") => {
                at = find(doc, at + 4, b"-->")? + 3;
            }
            Some(b'!' | b'/') | None => return Err(Malformed),
            Some(_) => return Ok(at),
        }
    }
}

/// One part of a start tag.
pub enum TagPart {
    /// An attribute.
    Attribute(Attribute),
    /// The tag's `>`: the offset past it, and whether the tag closed itself.
    End { after: usize, closed: bool },
}

/// The tag part at `at`, from just past the tag's name or its last
/// attribute, with `at` moved past it.
pub fn tag_part(doc: &[u8], at: &mut usize) -> Result<TagPart, Malformed> {
    let gap = *at;
    let mut i = space(doc, gap);
    match doc.get(i) {
        Some(b'>') => Ok(TagPart::End {
            after: i + 1,
            closed: false,
        }),
        Some(b'/') if doc.get(i + 1) == Some(&b'>') => Ok(TagPart::End {
            after: i + 2,
            closed: true,
        }),
        Some(_) if i > gap => {
            let start = i;
            while doc.get(i).is_some_and(|&b| attribute_name_byte(b)) {
                i += 1;
            }
            let name = start..i;
            i = space(doc, i);
            if name.is_empty() || doc.get(i) != Some(&b'=') {
                return Err(Malformed);
            }
            i = space(doc, i + 1);
            let quote = doc
                .get(i)
                .copied()
                .filter(|&b| b == b'"' || b == b'\'')
                .ok_or(Malformed)?;
            let end = find_byte(doc, i + 1, quote)?;
            let value = i + 1..end;
            if memchr(b'<', &doc[value.clone()]).is_some() {
                return Err(Malformed);
            }
            *at = end + 1;
            Ok(TagPart::Attribute(Attribute { name, value }))
        }
        _ => Err(Malformed),
    }
}

/// A namespace binding: a prefix, empty for the default, and its URI.
#[derive(Debug, Clone)]
struct Binding {
    prefix: Range<usize>,
    uri: Range<usize>,
}

/// An attribute of a tag: its name and its value between the quotes.
#[derive(Debug, Clone)]
pub struct Attribute {
    pub name: Range<usize>,
    pub value: Range<usize>,
}

/// One document's slots, from [`Paths::read`].
#[derive(Debug, Clone, Copy)]
pub struct Values<'s, 'a> {
    paths: &'s Paths,
    visits: &'s [Visit],
    attributes: &'s [Found],
    doc: &'a [u8],
}

impl<'a> Values<'_, 'a> {
    /// The slot for path `i`, in the order the set was built, or `None` past
    /// the last.
    ///
    /// A found value is checked here: its UTF-8, and for text, an empty
    /// element or an attribute, its entity references, so a bad one is
    /// [`Slot::Malformed`]. The read checks each element on a wanted path
    /// closes with its own name, and the attributes of any tag it reads an
    /// attribute or a namespace from. An element it skips is read by its
    /// tags' brackets and quotes only.
    #[must_use]
    pub fn get(&self, i: usize) -> Option<Slot<'a>> {
        self.paths.plans.get(i).map(|plan| self.slot(plan))
    }

    /// Every slot, in path order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Slot<'a>> {
        self.paths.plans.iter().map(|plan| self.slot(plan))
    }

    /// The number of slots.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.paths.plans.len()
    }

    /// Whether there are no slots.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.paths.plans.is_empty()
    }

    fn slot(&self, plan: &Plan) -> Slot<'a> {
        let mut parent = 0;
        for (i, &node) in plan.chain.iter().enumerate() {
            if self.visits[node].tag == 0 {
                let holder = self.visits[parent];
                return match (holder.closed, i, holder.kind) {
                    (false, _, _) => Slot::Malformed,
                    (true, 0, _) => Slot::MissingRoot,
                    (true, _, Some(Kind::Text)) => Slot::WrongParentType(i),
                    (true, _, _) => Slot::MissingField(i),
                };
            }
            parent = node;
        }
        if let Some(k) = plan.attribute {
            let found = &self.attributes[k];
            return match (&found.value, found.read) {
                (_, false) => Slot::Malformed,
                (None, true) => Slot::MissingField(plan.chain.len()),
                (Some(range), true) => self.found(range.clone(), Kind::Text, Source::Attribute),
            };
        }
        let visit = self.visits[parent];
        match visit.kind {
            Some(kind) if visit.closed => self.found(visit.start..visit.end, kind, Source::Content),
            _ => Slot::Malformed,
        }
    }

    fn found(&self, range: Range<usize>, kind: Kind, source: Source) -> Slot<'a> {
        let start = range.start;
        let bytes = &self.doc[range];
        let well_formed = match (source, kind) {
            (Source::Content, Kind::Element) => true,
            (Source::Content, _) => decode_text(bytes, |_| {}).is_ok(),
            (Source::Attribute, _) => decode_attribute(bytes, |_| {}).is_ok(),
        };
        match std::str::from_utf8(bytes) {
            Ok(text) if well_formed => Slot::Found(Raw {
                text,
                kind,
                start,
                source,
            }),
            _ => Slot::Malformed,
        }
    }
}

/// The document ends, or holds something that isn't XML, where a read needs
/// more.
#[derive(Debug)]
pub struct Malformed;

/// Whether a walk goes on, and from where.
type Next = Result<Option<usize>, Malformed>;

/// A read in progress.
struct Walk<'p, 'a, 's> {
    paths: &'p Paths,
    doc: &'a [u8],
    visits: &'s mut [Visit],
    attributes: &'s mut [Found],
    counts: &'s mut [usize],
    scope: &'s mut Vec<Binding>,
    tag: &'s mut Vec<Attribute>,
    /// Answers still owed. The walk stops at 0.
    left: usize,
}

impl Walk<'_, '_, '_> {
    /// Reads the prolog to the root element, then the root.
    fn document(&mut self) -> Result<(), Malformed> {
        self.child(0, prolog(self.doc)?)?;
        Ok(())
    }

    /// Reads the child element whose `<` is at `lt` below the walked element
    /// at `parent`, walks it for each node it matches, and skips it when it
    /// matches none. Gives the offset past its close, or `None` once the
    /// walk is done.
    fn child(&mut self, parent: usize, lt: usize) -> Next {
        let doc = self.doc;
        let paths = self.paths;
        let qname = lt + 1..name_end(doc, lt + 1)?;
        let local = local_name(&doc[qname.clone()]);
        let groups = paths.groups_of(parent, local);
        let parse = !groups.is_empty()
            && (paths.namespaced || paths.groups[groups.clone()].iter().any(|g| g.attributes));
        let scope = self.scope.len();
        let (content, closed) = if parse {
            let tag = self.read_tag(qname.end)?;
            if paths.namespaced {
                self.bind();
            }
            tag
        } else {
            tag_end(doc, qname.end)?
        };
        let mut matched = false;
        for g in groups.clone() {
            let group = &paths.groups[g];
            if let Some(uri) = &group.namespace
                && !self.element_in(&doc[qname.clone()], uri)?
            {
                continue;
            }
            let n = self.counts[g];
            self.counts[g] += 1;
            for selector in &paths.selects[group.selects.clone()] {
                if self.visits[selector.node].tag != 0 {
                    continue;
                }
                let hit = match &selector.select {
                    Select::Nth(k) => *k == n,
                    Select::Attribute(name, value) => self
                        .attribute(name)?
                        .map(|range| equal_decoded(&doc[range], value.as_bytes()))
                        .transpose()?
                        .unwrap_or(false),
                };
                if hit {
                    self.visits[selector.node].tag = lt + 1;
                    self.left -= 1;
                    matched = true;
                }
            }
        }
        if parent == 0 {
            // There's one root, so a root step it didn't match never will.
            self.visits[0].closed = true;
            self.close(0);
            if self.left == 0 {
                return Ok(None);
            }
        }
        if !matched {
            self.scope.truncate(scope);
            return if closed {
                Ok(Some(content))
            } else {
                pass(doc, content, None, false).map(|passed| Some(passed.after))
            };
        }
        let mut after = content;
        for g in groups {
            for selector in &paths.selects[paths.groups[g].selects.clone()] {
                if self.visits[selector.node].tag != lt + 1 {
                    continue;
                }
                match self.element(selector.node, qname.clone(), content, closed)? {
                    Some(next) => after = next,
                    None => return Ok(None),
                }
            }
        }
        self.scope.truncate(scope);
        Ok(Some(after))
    }

    /// Walks the element `node` matched, from its content at `content`, or
    /// from the end of its tag when `closed` says it closed itself.
    fn element(&mut self, node: usize, qname: Range<usize>, content: usize, closed: bool) -> Next {
        let doc = self.doc;
        let paths = self.paths;
        let info = &paths.nodes[node];
        if !info.attributes.is_empty() {
            self.read_tag(qname.end)?;
            for k in info.attributes.clone() {
                let value = self.attribute(&paths.attributes[k])?;
                self.attributes[k] = Found { read: true, value };
                self.left -= 1;
            }
            if self.left == 0 {
                return Ok(None);
            }
        }
        self.visits[node].start = content;
        if closed {
            self.shut(node, content, Kind::Empty);
            return Ok((self.left > 0).then_some(content));
        }
        let name = &doc[qname];
        let mut child = false;
        let mut text = false;
        let mut at = content;
        if !info.groups.is_empty() {
            for g in info.groups.clone() {
                self.counts[g] = 0;
            }
            let mut open = info.selects.len();
            while open > 0 {
                let lt = find_byte(doc, at, b'<')?;
                text = text || !blank(&doc[at..lt]);
                match doc.get(lt + 1) {
                    Some(b'/') => {
                        let after = close_tag(doc, lt, name)?;
                        self.shut(node, lt, kind(child, text));
                        return Ok((self.left > 0).then_some(after));
                    }
                    Some(b'!' | b'?') => {
                        let (after, cdata) = markup(doc, lt)?;
                        text = text || cdata.is_some_and(|c| !blank(&doc[c]));
                        at = after;
                    }
                    Some(_) => {
                        child = true;
                        match self.child(node, lt)? {
                            Some(next) => at = next,
                            None => return Ok(None),
                        }
                        open = paths.selects[info.selects.clone()]
                            .iter()
                            .filter(|s| self.visits[s.node].tag == 0)
                            .count();
                    }
                    None => return Err(Malformed),
                }
            }
        }
        let passed = pass(doc, at, Some(name), info.leaf)?;
        self.shut(
            node,
            passed.end,
            kind(child || passed.child, text || passed.text),
        );
        Ok((self.left > 0).then_some(passed.after))
    }

    /// Records the element at `node` as passed, its content ending at `end`,
    /// and settles what it owes.
    fn shut(&mut self, node: usize, end: usize, kind: Kind) {
        let visit = &mut self.visits[node];
        visit.end = end;
        visit.kind = Some(kind);
        visit.closed = true;
        self.close(node);
    }

    /// Settles what `node` owes once it can match no more children: its leaf
    /// answer, and every answer below a child it didn't find.
    fn close(&mut self, node: usize) {
        let paths = self.paths;
        let info = &paths.nodes[node];
        let mut settled = usize::from(info.leaf);
        for selector in &paths.selects[info.selects.clone()] {
            if self.visits[selector.node].tag == 0 {
                settled += paths.nodes[selector.node].pending;
            }
        }
        self.left -= settled;
    }

    /// Reads a tag's attributes into `self.tag`, from just past its name, and
    /// gives the offset past the tag and whether it closed itself.
    fn read_tag(&mut self, from: usize) -> Result<(usize, bool), Malformed> {
        self.tag.clear();
        let mut at = from;
        loop {
            match tag_part(self.doc, &mut at)? {
                TagPart::Attribute(attribute) => self.tag.push(attribute),
                TagPart::End { after, closed } => return Ok((after, closed)),
            }
        }
    }

    /// Puts the namespace declarations in `self.tag` in scope.
    fn bind(&mut self) {
        let doc = self.doc;
        for attribute in self.tag.as_slice() {
            let name = &doc[attribute.name.clone()];
            let prefix = if name == b"xmlns" {
                attribute.name.end..attribute.name.end
            } else if name.starts_with(b"xmlns:") {
                attribute.name.start + 6..attribute.name.end
            } else {
                continue;
            };
            self.scope.push(Binding {
                prefix,
                uri: attribute.value.clone(),
            });
        }
    }

    /// Whether the qualified name `qname` is in the namespace `uri`, read
    /// through the bindings in scope.
    fn element_in(&self, qname: &[u8], uri: &str) -> Result<bool, Malformed> {
        let prefix = memchr(b':', qname).map_or(&qname[..0], |i| &qname[..i]);
        self.prefix_in(prefix, uri)
    }

    /// Whether `prefix`, empty for the default, is bound to `uri`.
    fn prefix_in(&self, prefix: &[u8], uri: &str) -> Result<bool, Malformed> {
        if prefix == b"xml" {
            return Ok(uri == XML_NAMESPACE);
        }
        let doc = self.doc;
        let bound = self
            .scope
            .iter()
            .rev()
            .find(|b| &doc[b.prefix.clone()] == prefix);
        match bound {
            None if prefix.is_empty() => Ok(false),
            None => Err(Malformed),
            Some(b) => equal_decoded(&doc[b.uri.clone()], uri.as_bytes()),
        }
    }

    /// The value of the first attribute in `self.tag` that `name` matches,
    /// namespace declarations aside. An attribute with no prefix is in no
    /// namespace.
    fn attribute(&self, name: &Name) -> Result<Option<Range<usize>>, Malformed> {
        let doc = self.doc;
        for attribute in self.tag.as_slice() {
            let qname = &doc[attribute.name.clone()];
            if qname == b"xmlns" || qname.starts_with(b"xmlns:") {
                continue;
            }
            if local_name(qname) != name.local.as_bytes() {
                continue;
            }
            let hit = match (&name.namespace, memchr(b':', qname)) {
                (None, _) => true,
                (Some(_), None) => false,
                (Some(uri), Some(i)) => self.prefix_in(&qname[..i], uri)?,
            };
            if hit {
                return Ok(Some(attribute.value.clone()));
            }
        }
        Ok(None)
    }
}

/// A content's kind from whether it holds a child element and text.
const fn kind(child: bool, text: bool) -> Kind {
    match (child, text) {
        (true, _) => Kind::Element,
        (false, true) => Kind::Text,
        (false, false) => Kind::Empty,
    }
}

/// An element's content passed to its close.
pub struct Passed {
    /// The `<` of the close tag.
    pub end: usize,
    /// Just past the close tag.
    pub after: usize,
    pub child: bool,
    text: bool,
}

/// Passes an element's content from `at`, depth 1, to just past its close
/// tag, counting tag starts and ends with no name read. `name` is checked
/// against the close tag when given, and `track` notes child elements and
/// text at depth 1.
pub fn pass(
    doc: &[u8],
    mut at: usize,
    name: Option<&[u8]>,
    track: bool,
) -> Result<Passed, Malformed> {
    let mut depth = 1_usize;
    let mut child = false;
    let mut text = false;
    loop {
        let lt = find_byte(doc, at, b'<')?;
        if track && depth == 1 && !text {
            text = !blank(&doc[at..lt]);
        }
        match doc.get(lt + 1) {
            Some(b'/') => {
                depth -= 1;
                if depth == 0 {
                    let after = match name {
                        Some(name) => close_tag(doc, lt, name)?,
                        None => find_byte(doc, lt + 2, b'>')? + 1,
                    };
                    return Ok(Passed {
                        end: lt,
                        after,
                        child,
                        text,
                    });
                }
                at = find_byte(doc, lt + 2, b'>')? + 1;
            }
            Some(b'!' | b'?') => {
                let (after, cdata) = markup(doc, lt)?;
                if track && depth == 1 && !text {
                    text = cdata.is_some_and(|c| !blank(&doc[c]));
                }
                at = after;
            }
            Some(_) => {
                let (after, closed) = tag_end(doc, lt + 1)?;
                child |= depth == 1;
                depth += usize::from(!closed);
                at = after;
            }
            None => return Err(Malformed),
        }
    }
}

/// Passes the comment, CDATA section or processing instruction whose `<` is
/// at `lt`. Gives the offset past it, and a CDATA section's contents.
pub fn markup(doc: &[u8], lt: usize) -> Result<(usize, Option<Range<usize>>), Malformed> {
    let rest = &doc[lt..];
    if rest.starts_with(b"<?") {
        Ok((find(doc, lt + 2, b"?>")? + 2, None))
    } else if rest.starts_with(b"<!--") {
        Ok((find(doc, lt + 4, b"-->")? + 3, None))
    } else if rest.starts_with(b"<![CDATA[") {
        let end = find(doc, lt + 9, b"]]>")?;
        Ok((end + 3, Some(lt + 9..end)))
    } else {
        Err(Malformed)
    }
}

/// The offset past the close tag at `lt`, once its name is checked as `name`.
pub fn close_tag(doc: &[u8], lt: usize, name: &[u8]) -> Result<usize, Malformed> {
    let from = lt + 2;
    let end = from + name.len();
    if doc.get(from..end) != Some(name) {
        return Err(Malformed);
    }
    let at = space(doc, end);
    if doc.get(at) != Some(&b'>') {
        return Err(Malformed);
    }
    Ok(at + 1)
}

/// The offset past the tag whose name ends before `from`, found by its
/// brackets and quotes, and whether it closed itself.
pub fn tag_end(doc: &[u8], mut from: usize) -> Result<(usize, bool), Malformed> {
    loop {
        let rest = doc.get(from..).ok_or(Malformed)?;
        let i = memchr3(b'"', b'\'', b'>', rest).ok_or(Malformed)?;
        let at = from + i;
        if doc[at] == b'>' {
            return Ok((at + 1, at > 0 && doc[at - 1] == b'/'));
        }
        from = find_byte(doc, at + 1, doc[at])? + 1;
    }
}

/// The offset past the element name that starts at `from`.
pub fn name_end(doc: &[u8], from: usize) -> Result<usize, Malformed> {
    let rest = doc.get(from..).ok_or(Malformed)?;
    let len = rest
        .iter()
        .position(|&b| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'/' | b'>'))
        .ok_or(Malformed)?;
    if len == 0 {
        return Err(Malformed);
    }
    Ok(from + len)
}

/// A qualified name's local part.
pub fn local_name(qname: &[u8]) -> &[u8] {
    memchr(b':', qname).map_or(qname, |i| &qname[i + 1..])
}

const fn attribute_name_byte(b: u8) -> bool {
    !matches!(
        b,
        b' ' | b'\t' | b'\n' | b'\r' | b'=' | b'>' | b'/' | b'"' | b'\'' | b'<'
    )
}

/// The offset of the first `byte` at or after `from`.
#[inline]
pub fn find_byte(doc: &[u8], from: usize, byte: u8) -> Result<usize, Malformed> {
    let rest = doc.get(from..).ok_or(Malformed)?;
    memchr(byte, rest).map(|i| from + i).ok_or(Malformed)
}

/// The offset of the first `needle` at or after `from`.
fn find(doc: &[u8], from: usize, needle: &[u8]) -> Result<usize, Malformed> {
    let rest = doc.get(from..).ok_or(Malformed)?;
    memmem::find(rest, needle)
        .map(|i| from + i)
        .ok_or(Malformed)
}

/// The offset of the first byte at or after `at` that isn't XML whitespace.
#[inline]
fn space(doc: &[u8], mut at: usize) -> usize {
    while let Some(b' ' | b'\t' | b'\n' | b'\r') = doc.get(at) {
        at += 1;
    }
    at
}

/// Whether text is all whitespace, read through any character reference.
fn blank(text: &[u8]) -> bool {
    let mut at = 0;
    while let Some(&b) = text.get(at) {
        match b {
            b' ' | b'\t' | b'\n' | b'\r' => at += 1,
            b'&' => match entity(&text[at + 1..]) {
                Some((' ' | '\t' | '\n' | '\r', len)) => at += 1 + len,
                _ => return false,
            },
            _ => return false,
        }
    }
    true
}

/// Whether an attribute value byte needs decoding.
pub const fn attribute_special(b: u8) -> bool {
    matches!(b, b'&' | b'\t' | b'\n' | b'\r' | b'<')
}

/// The character the reference after an `&` spells, and its length with its
/// `;`. The five predefined entities and character references only.
fn entity(raw: &[u8]) -> Option<(char, usize)> {
    let semi = memchr(b';', &raw[..raw.len().min(32)])?;
    let name = &raw[..semi];
    let c = match name {
        b"lt" => '<',
        b"gt" => '>',
        b"amp" => '&',
        b"apos" => '\'',
        b"quot" => '"',
        [b'#', b'x', hex @ ..] => code(hex, 16)?,
        [b'#', digits @ ..] => code(digits, 10)?,
        _ => return None,
    };
    Some((c, semi + 1))
}

/// A character reference's digits read in `radix`, when it names a
/// character XML allows.
fn code(digits: &[u8], radix: u32) -> Option<char> {
    if digits.is_empty() {
        return None;
    }
    let value = digits.iter().try_fold(0_u32, |acc, &b| {
        let digit = char::from(b).to_digit(radix)?;
        acc.checked_mul(radix)?.checked_add(digit)
    })?;
    let c = char::from_u32(value)?;
    let allowed =
        matches!(c, '\t' | '\n' | '\r') || (c >= ' ' && !matches!(c, '\u{FFFE}' | '\u{FFFF}'));
    allowed.then_some(c)
}

/// Hands each decoded piece of `run` to `out`, with `\r\n` and a lone `\r`
/// read as one `\n`.
fn line_ends(mut run: &[u8], out: &mut impl FnMut(&[u8])) {
    while let Some(i) = memchr(b'\r', run) {
        out(&run[..i]);
        out(b"\n");
        let skip = if run.get(i + 1) == Some(&b'\n') { 2 } else { 1 };
        run = &run[i + skip..];
    }
    out(run);
}

/// Decodes an element's content with no child elements, handing each piece
/// to `out`: entities decoded, line ends read as `\n`, CDATA kept, comments
/// and processing instructions dropped. A bad reference or tag is malformed.
pub fn decode_text(raw: &[u8], mut out: impl FnMut(&[u8])) -> Result<(), Malformed> {
    let mut at = 0;
    while at < raw.len() {
        let Some(i) = memchr2(b'&', b'<', &raw[at..]) else {
            line_ends(&raw[at..], &mut out);
            return Ok(());
        };
        line_ends(&raw[at..at + i], &mut out);
        at += i;
        if raw[at] == b'&' {
            let (c, len) = entity(&raw[at + 1..]).ok_or(Malformed)?;
            out(c.encode_utf8(&mut [0; 4]).as_bytes());
            at += 1 + len;
        } else {
            let (after, cdata) = markup(raw, at)?;
            if let Some(range) = cdata {
                line_ends(&raw[range], &mut out);
            }
            at = after;
        }
    }
    Ok(())
}

/// Decodes an attribute value, handing each piece to `out`: entities
/// decoded, and a tab, `\n`, `\r` or `\r\n` read as one space. A bad
/// reference or a `<` is malformed.
pub fn decode_attribute(raw: &[u8], mut out: impl FnMut(&[u8])) -> Result<(), Malformed> {
    let mut at = 0;
    loop {
        let rest = &raw[at..];
        let Some(i) = rest.iter().position(|&b| attribute_special(b)) else {
            out(rest);
            return Ok(());
        };
        out(&rest[..i]);
        at += i;
        match raw[at] {
            b'&' => {
                let (c, len) = entity(&raw[at + 1..]).ok_or(Malformed)?;
                out(c.encode_utf8(&mut [0; 4]).as_bytes());
                at += 1 + len;
            }
            b'<' => return Err(Malformed),
            b'\r' if raw.get(at + 1) == Some(&b'\n') => {
                out(b" ");
                at += 2;
            }
            _ => {
                out(b" ");
                at += 1;
            }
        }
    }
}

/// Whether the attribute value `raw` decodes to `want`.
pub fn equal_decoded(raw: &[u8], want: &[u8]) -> Result<bool, Malformed> {
    if !raw.iter().any(|&b| attribute_special(b)) {
        return Ok(raw == want);
    }
    let mut at = 0;
    let mut equal = true;
    decode_attribute(raw, |part| {
        if equal && want.get(at..at + part.len()) == Some(part) {
            at += part.len();
        } else {
            equal = false;
        }
    })?;
    Ok(equal && at == want.len())
}

#[cfg(test)]
mod tests;