Skip to main content

quarb_xml/
lib.rs

1//! XML adapter for Quarb.
2//!
3//! Maps a well-formed XML document onto the arbor model, parsing
4//! with `quick-xml`. Unlike the HTML adapter, parsing is strict:
5//! mismatched or unclosed tags, duplicate attributes, and unknown
6//! entity references are errors.
7//!
8//! - Elements are the nodes; text, CDATA, comments, processing
9//!   instructions, and the doctype are not navigated (text is
10//!   exposed as a projection instead).
11//! - A node's *name* is its tag exactly as written, including any
12//!   namespace prefix (`dc:title`). Prefixes are not resolved to
13//!   URIs. Since `:` is not a bare-name character in Quarb, a
14//!   prefixed name is navigated with a quoted segment
15//!   (`//'dc:title'`); `:::local-name` and `:::ns-prefix` metadata
16//!   allow prefix-agnostic filtering (`//*[:::local-name =
17//!   "title"]`). The document root is unnamed; the document
18//!   element is its single child.
19//! - The traits are few: the root wears `document`, every element
20//!   `element`, and a `table` element `tabula` as well. XML has no
21//!   universal structural vocabulary beyond that; the leaf and
22//!   container distinctions are core metadata (`:is-leaf`,
23//!   `:n-children`).
24//! - Attributes are properties: `::pages`, `::href`. The default
25//!   projection (`::`) and `::text` are the element's text
26//!   content; `:::tag`, `:::id`, `:::local-name`, `:::ns-prefix`,
27//!   `:::n-attrs`, and any `:::attr` expose metadata; `:::texts`
28//!   is the list of the element's immediate text runs (XPath's
29//!   `text()`).
30//! - An attribute holding an ID reference resolves: `::ref-->`
31//!   follows a bare IDREF value (`book="b1"`) or a fragment
32//!   (`href="#b1"`) to the element with that `id` or `xml:id`.
33//! - Input is UTF-8 text; an `encoding` declaration in the XML
34//!   prologue is ignored. Only the five predefined entities and
35//!   numeric character references are resolved.
36
37use quarb::names::Names;
38use quarb::{AstAdapter, NodeId, Value};
39use quick_xml::escape::resolve_predefined_entity;
40use quick_xml::events::{BytesStart, Event};
41use quick_xml::{Decoder, Reader};
42use std::collections::HashMap;
43
44/// The text with its white space collapsed to single spaces and
45/// trimmed; `None` when nothing is left.
46fn collapsed(text: &str) -> Option<String> {
47    let mut words = text.split_whitespace();
48    let mut out = words.next()?.to_string();
49    for w in words {
50        out.push(' ');
51        out.push_str(w);
52    }
53    Some(out)
54}
55
56struct Node {
57    /// The tag name as written, in the document's name table;
58    /// `None` for the document root.
59    tag: Option<u32>,
60    /// The attributes: the name in the table, the value.
61    attrs: Vec<(u32, String)>,
62    /// The element's text content (all descendant text and CDATA,
63    /// concatenated in document order).
64    text: String,
65    /// Where this element's text starts within its parent's: the
66    /// parent's own text runs are what its children's texts leave
67    /// (`:::texts`).
68    at: u32,
69    parent: Option<NodeId>,
70    children: Vec<NodeId>,
71}
72
73impl Node {
74    fn attr(&self, names: &Names, name: &str) -> Option<&str> {
75        let k = names.key(name)?;
76        self.attrs
77            .iter()
78            .find(|(a, _)| *a == k)
79            .map(|(_, v)| v.as_str())
80    }
81}
82
83/// An error building an [`XmlAdapter`] from document text.
84#[derive(Debug, thiserror::Error)]
85pub enum XmlError {
86    #[error(transparent)]
87    Syntax(#[from] quick_xml::Error),
88    #[error("unknown entity reference '&{0};'")]
89    UnknownEntity(String),
90    #[error("unclosed element '<{0}>'")]
91    Unclosed(String),
92    #[error("no root element")]
93    NoRoot,
94    #[error("content after the root element")]
95    TrailingContent,
96}
97
98/// The encoding an XML document declares in its prologue
99/// (`<?xml version="1.0" encoding="windows-1251"?>`), reported for
100/// the engine's source boundary. The adapter decodes nothing: the
101/// boundary applies the declaration after `?encoding=` and a
102/// byte-order mark have had their say. The prologue is scanned as
103/// ASCII-compatible bytes, as the XML recommendation's appendix F
104/// reads it; a document whose first bytes are not `<?xml` declares
105/// nothing.
106pub fn declared_encoding(bytes: &[u8]) -> Option<String> {
107    quarb::source::xml_declared_encoding(bytes)
108}
109
110/// A Quarb adapter over a parsed XML document.
111pub struct XmlAdapter {
112    nodes: Vec<Node>,
113    /// The document's tag and attribute names, each once.
114    names: Names,
115    /// `id` / `xml:id` attribute value → the element carrying it.
116    ids: HashMap<String, NodeId>,
117    root: NodeId,
118}
119
120impl XmlAdapter {
121    /// Parse `xml` and build the adapter. The document must be
122    /// well-formed: exactly one root element, matched tags, unique
123    /// attributes, and only predefined or numeric entities.
124    pub fn parse(xml: &str) -> Result<Self, XmlError> {
125        let mut nodes = vec![Node {
126            tag: None,
127            attrs: Vec::new(),
128            text: String::new(),
129            at: 0,
130            parent: None,
131            children: Vec::new(),
132        }];
133        let mut ids = HashMap::new();
134        let root = NodeId(0);
135
136        let mut names = Names::new();
137        let mut reader = Reader::from_str(xml);
138        let decoder = reader.decoder();
139        // Indices of the currently open elements; the synthetic
140        // root stays at the bottom.
141        let mut stack: Vec<usize> = vec![0];
142
143        loop {
144            match reader.read_event()? {
145                Event::Start(e) => {
146                    let idx = intern(&mut nodes, &mut names, &mut ids, &stack, decoder, &e)?;
147                    stack.push(idx);
148                }
149                Event::Empty(e) => {
150                    intern(&mut nodes, &mut names, &mut ids, &stack, decoder, &e)?;
151                }
152                Event::End(_) => {
153                    let closed = stack.pop().expect("end event matches an open element");
154                    let text = std::mem::take(&mut nodes[closed].text);
155                    let parent = *stack.last().expect("stack holds the root");
156                    nodes[parent].text.push_str(&text);
157                    nodes[closed].text = text;
158                }
159                Event::Text(e) => {
160                    let open = *stack.last().expect("stack holds the root");
161                    let text = e.xml_content().map_err(quick_xml::Error::from)?;
162                    nodes[open].text.push_str(&text);
163                }
164                Event::CData(e) => {
165                    let open = *stack.last().expect("stack holds the root");
166                    let text = e.decode().map_err(quick_xml::Error::from)?;
167                    nodes[open].text.push_str(&text);
168                }
169                Event::GeneralRef(e) => {
170                    let open = *stack.last().expect("stack holds the root");
171                    if let Some(ch) = e.resolve_char_ref()? {
172                        nodes[open].text.push(ch);
173                    } else {
174                        let name = e.decode().map_err(quick_xml::Error::from)?;
175                        let Some(resolved) = resolve_predefined_entity(&name) else {
176                            return Err(XmlError::UnknownEntity(name.into_owned()));
177                        };
178                        nodes[open].text.push_str(resolved);
179                    }
180                }
181                Event::Decl(_) | Event::PI(_) | Event::Comment(_) | Event::DocType(_) => {}
182                Event::Eof => break,
183            }
184        }
185
186        if stack.len() > 1 {
187            let open = stack.pop().expect("checked non-root");
188            let tag = nodes[open].tag.expect("open elements are tagged");
189            return Err(XmlError::Unclosed(names.get(tag).to_string()));
190        }
191        match nodes[0].children.len() {
192            0 => return Err(XmlError::NoRoot),
193            1 => {}
194            _ => return Err(XmlError::TrailingContent),
195        }
196        // The synthetic root's text is the document element's, not
197        // any stray whitespace around it.
198        nodes[0].text = nodes[nodes[0].children[0].0 as usize].text.clone();
199
200        Ok(XmlAdapter {
201            nodes,
202            names,
203            ids,
204            root,
205        })
206    }
207
208    /// A locator path to `node`, like `/library/book[2]/author`, for
209    /// rendering. A `[n]` index is added only to disambiguate
210    /// same-tag siblings.
211    /// The element carrying `id` / `xml:id` = `id`, if any.
212    pub fn node_by_id(&self, id: &str) -> Option<NodeId> {
213        self.ids.get(id).copied()
214    }
215
216    pub fn locator(&self, node: NodeId) -> String {
217        let mut segments = Vec::new();
218        let mut cur = Some(node);
219        while let Some(id) = cur {
220            let n = &self.nodes[id.0 as usize];
221            if let Some(tag) = n.tag {
222                segments.push(self.segment(id, tag));
223            }
224            cur = n.parent;
225        }
226        segments.reverse();
227        format!("/{}", segments.join("/"))
228    }
229
230    fn segment(&self, node: NodeId, tag: u32) -> String {
231        let name = self.names.get(tag);
232        let Some(parent) = self.nodes[node.0 as usize].parent else {
233            return name.to_string();
234        };
235        let siblings = &self.nodes[parent.0 as usize].children;
236        let same_tag: Vec<NodeId> = siblings
237            .iter()
238            .copied()
239            .filter(|&s| self.nodes[s.0 as usize].tag == Some(tag))
240            .collect();
241        if same_tag.len() > 1 {
242            let n = same_tag.iter().position(|&s| s == node).unwrap() + 1;
243            format!("{name}[{n}]")
244        } else {
245            name.to_string()
246        }
247    }
248}
249
250/// Intern the element behind a `Start`/`Empty` event as a child of
251/// the innermost open element, returning its arena index.
252fn intern(
253    nodes: &mut Vec<Node>,
254    names: &mut Names,
255    ids: &mut HashMap<String, NodeId>,
256    stack: &[usize],
257    decoder: Decoder,
258    e: &BytesStart,
259) -> Result<usize, XmlError> {
260    let idx = nodes.len();
261    let this = NodeId(idx as u64);
262    let tag = names.intern(
263        &decoder
264            .decode(e.name().as_ref())
265            .map_err(quick_xml::Error::from)?,
266    );
267    let mut attrs = Vec::new();
268    for attr in e.attributes() {
269        let attr = attr.map_err(quick_xml::Error::from)?;
270        let key = decoder
271            .decode(attr.key.as_ref())
272            .map_err(quick_xml::Error::from)?
273            .into_owned();
274        let value = attr.decode_and_unescape_value(decoder)?.into_owned();
275        if key == "id" || key == "xml:id" {
276            ids.entry(value.clone()).or_insert(this);
277        }
278        attrs.push((names.intern(&key), value));
279    }
280    let parent = *stack.last().expect("stack holds the root");
281    // (the parent's text stands still while this element is open)
282    let at = u32::try_from(nodes[parent].text.len()).unwrap_or(u32::MAX);
283    nodes.push(Node {
284        tag: Some(tag),
285        attrs,
286        text: String::new(),
287        at,
288        parent: Some(NodeId(parent as u64)),
289        children: Vec::new(),
290    });
291    nodes[parent].children.push(this);
292    Ok(idx)
293}
294
295/// The name before / after the first `:` of a qualified name.
296fn split_qualified(tag: &str) -> (Option<&str>, &str) {
297    match tag.split_once(':') {
298        Some((prefix, local)) => (Some(prefix), local),
299        None => (None, tag),
300    }
301}
302
303impl AstAdapter for XmlAdapter {
304    /// The arena knows how many nodes a step reaches; nothing is read.
305    fn estimate(&self, scope: &[&str], plan: &quarb::StepPlan<'_>) -> Option<quarb::Estimate> {
306        quarb::adapter::arena_estimate(self, scope, plan, quarb::Latency::Memory, None)
307    }
308
309    fn root(&self) -> NodeId {
310        self.root
311    }
312
313    /// In memory: an unscoped reverse resolution or value match may
314    /// walk the arbor.
315    fn walks_for_references(&self) -> bool {
316        true
317    }
318
319    fn children(&self, node: NodeId) -> Vec<NodeId> {
320        self.nodes[node.0 as usize].children.clone()
321    }
322
323    fn name(&self, node: NodeId) -> Option<String> {
324        self.nodes[node.0 as usize]
325            .tag
326            .map(|t| self.names.get(t).to_string())
327    }
328
329    /// The kind first (spec: Traits): `document` for the root,
330    /// `element` for every element (its name is the document's
331    /// vocabulary, not the adapter's). A `table` element (TEI,
332    /// DocBook, HTML in XML) then carries `tabula`, the one trait
333    /// a table has in every substrate (spec: The Table):
334    /// `//*<tabula>` finds it, `| #` reads it.
335    fn traits(&self, node: NodeId) -> Vec<String> {
336        let Some(name) = self.name(node) else {
337            return vec!["document".to_string()];
338        };
339        let local = name.rsplit(':').next().unwrap_or("");
340        let mut out = vec!["element".to_string()];
341        if local == "table" {
342            out.push("tabula".to_string());
343        }
344        out
345    }
346
347    fn parent(&self, node: NodeId) -> Option<NodeId> {
348        self.nodes[node.0 as usize].parent
349    }
350
351    /// `::text` is the element's text content; any other name is an
352    /// attribute value.
353    /// Attributes, by name (`::pages`). Element text is the bare
354    /// projection (`::`) — no attribute name is shadowed.
355    /// XML's own reference syntax: XLink's `xlink:href`, else a
356    /// plain `href`. The bare arrows read it.
357    fn ref_property(&self, node: NodeId) -> Option<String> {
358        let n = &self.nodes[node.0 as usize];
359        ["xlink:href", "href"]
360            .into_iter()
361            .find(|a| n.attr(&self.names, a).is_some())
362            .map(str::to_string)
363    }
364
365    /// An element's properties are its attributes.
366    fn property_names(&self, node: NodeId) -> Vec<String> {
367        self.nodes[node.0 as usize]
368            .attrs
369            .iter()
370            .map(|(k, _)| self.names.get(*k).to_string())
371            .collect()
372    }
373
374    /// Any attribute may hold a reference (`#id`, an IDREF) to any
375    /// element of the document: the format declares no narrower one.
376    fn can_refer_to(&self, _source: NodeId, _target: NodeId) -> Option<bool> {
377        Some(true)
378    }
379
380    fn property(&self, node: NodeId, name: &str) -> Option<Value> {
381        self.nodes[node.0 as usize]
382            .attr(&self.names, name)
383            .map(|v| Value::Str(v.to_string()))
384    }
385
386    /// The default projection of an element is its text content.
387    fn default_value(&self, node: NodeId) -> Option<Value> {
388        Some(Value::Str(self.nodes[node.0 as usize].text.clone()))
389    }
390
391    /// `:::tag`, `:::local-name`, `:::ns-prefix`, and `:::n-attrs`
392    /// — facts about the element, never its data: attributes are
393    /// properties (`::pages`), text is the bare projection.
394    /// `:::texts` is the structural reading of the text beside the
395    /// bare projection's (ruling 2026-11-11): XPath's `text()`, the
396    /// list of the element's immediate text runs, no child
397    /// element's text in it; each run with its white space
398    /// collapsed and trimmed, null where there is none.
399    /// The `:::` keys this adapter answers (`:meta` lists the ones
400    /// a node answers).
401    fn metadata_catalogue(&self) -> &'static [&'static str] {
402        &["tag", "local-name", "ns-prefix", "n-attrs", "texts"]
403    }
404
405    fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
406        let n = &self.nodes[node.0 as usize];
407        match key {
408            "texts" => {
409                n.tag?;
410                // the element's text less its children's, in order
411                let mut runs = Vec::new();
412                let mut from = 0;
413                for c in &n.children {
414                    let c = &self.nodes[c.0 as usize];
415                    let at = (c.at as usize).min(n.text.len());
416                    runs.extend(collapsed(n.text.get(from..at).unwrap_or("")));
417                    from = (at + c.text.len()).min(n.text.len());
418                }
419                runs.extend(collapsed(n.text.get(from..).unwrap_or("")));
420                (!runs.is_empty()).then(|| Value::list(runs.into_iter().map(Value::Str).collect()))
421            }
422            "tag" => n.tag.map(|t| Value::Str(self.names.get(t).to_string())),
423            "local-name" => n
424                .tag
425                .map(|t| Value::Str(split_qualified(self.names.get(t)).1.to_string())),
426            "ns-prefix" => n
427                .tag
428                .and_then(|t| split_qualified(self.names.get(t)).0)
429                .map(|p| Value::Str(p.to_string())),
430            "n-attrs" => Some(Value::Int(n.attrs.len() as i64)),
431            _ => None,
432        }
433    }
434
435    /// Follow an attribute that is an ID reference — a bare IDREF
436    /// value (`book="b1"`) or a fragment (`href="#b1"`) — to the
437    /// element carrying that `id` or `xml:id`.
438    fn resolve(&self, node: NodeId, property: &str, _hint: Option<&str>) -> Option<NodeId> {
439        let value = self.nodes[node.0 as usize].attr(&self.names, property)?;
440        let target = value.strip_prefix('#').unwrap_or(value);
441        self.ids.get(target).copied()
442    }
443}
444
445/// An XML document with one repeated child streamed (hash (d) of the
446/// columnar round, 2026-11-06): the document element's children —
447/// `<page>` under `<mediawiki>`, `<entry>` under `<dictionary>` — as
448/// byte spans found by one pass of the reader, each parsed into its
449/// own arbor when a step reaches it, wrapped in the document
450/// element's own start tag so its prefixes resolve as in the whole
451/// parse; the document element itself, its attributes and the
452/// prologue parsed whole as the PREFIX document with the children
453/// left out. The node ids pack the child's index above its arbor's
454/// node; the prefix's nodes keep their own ids below.
455pub struct XmlStream {
456    size: u64,
457    /// The prologue and the document element, childless.
458    prefix: XmlAdapter,
459    /// The document element in the prefix: the children's parent.
460    anchor: NodeId,
461    /// The document element's start and end tags, as written.
462    root_start: String,
463    root_end: String,
464    /// The children's spans and their tags (interned).
465    offsets: Vec<(u64, u32)>,
466    tags: Vec<u32>,
467    tag_names: Vec<String>,
468    /// The whitespace text of the document element between its
469    /// children, one piece before each child and one after the last.
470    gaps: Vec<String>,
471    /// `id` / `xml:id` values anywhere in the children → the child.
472    ids: HashMap<String, u32>,
473    last: std::cell::RefCell<Option<(u32, XmlAdapter)>>,
474    reader: std::cell::RefCell<(quarb::source::Window, u32)>,
475}
476
477const CHILD_SHIFT: u32 = 32;
478
479impl XmlStream {
480    /// The file scanned for its document element's children; `None`
481    /// where the document is not of that shape (text beside the
482    /// children, no children, or children under half the file),
483    /// where the whole read is the right one.
484    pub fn open(path: &std::path::Path) -> Result<Option<Self>, XmlError> {
485        let bytes =
486            std::fs::read(path).map_err(|e| quick_xml::Error::Io(std::sync::Arc::new(e)))?;
487        let size = bytes.len() as u64;
488        let mut reader = Reader::from_reader(std::io::Cursor::new(&bytes));
489        let decoder = reader.decoder();
490        let mut buf = Vec::new();
491        let mut depth = 0usize;
492        let mut root_span: Option<(usize, usize)> = None; // the start tag's bytes
493        let mut root_end_span: Option<(usize, usize)> = None;
494        let mut root_tag: Option<String> = None;
495        let mut offsets: Vec<(u64, u32)> = Vec::new();
496        let mut tags: Vec<u32> = Vec::new();
497        let mut tag_names: Vec<String> = Vec::new();
498        let mut tag_index: HashMap<String, u32> = HashMap::new();
499        let mut gaps: Vec<String> = vec![String::new()];
500        let mut ids: HashMap<String, u32> = HashMap::new();
501        let mut child_start: usize = 0;
502        let mut intern_tag = |name: &str| -> u32 {
503            if let Some(&k) = tag_index.get(name) {
504                return k;
505            }
506            let k = tag_names.len() as u32;
507            tag_names.push(name.to_string());
508            tag_index.insert(name.to_string(), k);
509            k
510        };
511        loop {
512            let before = reader.buffer_position() as usize;
513            let event = reader.read_event_into(&mut buf)?;
514            let after = reader.buffer_position() as usize;
515            match event {
516                // the document element: its start tag kept; childless
517                // (`<root/>`) it has nothing to stream
518                Event::Empty(_) if depth == 0 => return Ok(None),
519                Event::Start(e) if depth == 0 => {
520                    root_tag = Some(
521                        decoder
522                            .decode(e.name().as_ref())
523                            .map_err(quick_xml::Error::from)?
524                            .into_owned(),
525                    );
526                    root_span = Some((before, after));
527                    depth = 1;
528                }
529                // a child of the document element: its span opened, or
530                // whole when empty
531                Event::Start(e) | Event::Empty(e) if depth == 1 => {
532                    let empty = bytes[before..after].ends_with(b"/>");
533                    child_start = before;
534                    let name = decoder
535                        .decode(e.name().as_ref())
536                        .map_err(quick_xml::Error::from)?
537                        .into_owned();
538                    let k = intern_tag(&name);
539                    let i = offsets.len() as u32;
540                    for attr in e.attributes() {
541                        let attr = attr.map_err(quick_xml::Error::from)?;
542                        let key = decoder
543                            .decode(attr.key.as_ref())
544                            .map_err(quick_xml::Error::from)?;
545                        if key == "id" || key == "xml:id" {
546                            let v = attr.decode_and_unescape_value(decoder)?.into_owned();
547                            ids.entry(v).or_insert(i);
548                        }
549                    }
550                    tags.push(k);
551                    if empty {
552                        offsets.push((before as u64, (after - before) as u32));
553                        gaps.push(String::new());
554                    } else {
555                        depth = 2;
556                        offsets.push((before as u64, 0));
557                    }
558                }
559                Event::Start(e) => {
560                    for attr in e.attributes() {
561                        let attr = attr.map_err(quick_xml::Error::from)?;
562                        let key = decoder
563                            .decode(attr.key.as_ref())
564                            .map_err(quick_xml::Error::from)?;
565                        if key == "id" || key == "xml:id" {
566                            let v = attr.decode_and_unescape_value(decoder)?.into_owned();
567                            ids.entry(v).or_insert(offsets.len() as u32 - 1);
568                        }
569                    }
570                    depth += 1;
571                }
572                Event::Empty(e) => {
573                    for attr in e.attributes() {
574                        let attr = attr.map_err(quick_xml::Error::from)?;
575                        let key = decoder
576                            .decode(attr.key.as_ref())
577                            .map_err(quick_xml::Error::from)?;
578                        if key == "id" || key == "xml:id" {
579                            let v = attr.decode_and_unescape_value(decoder)?.into_owned();
580                            ids.entry(v).or_insert(offsets.len() as u32 - 1);
581                        }
582                    }
583                }
584                Event::End(_) => {
585                    if depth == 2 {
586                        let last = offsets.last_mut().expect("an open child");
587                        last.1 = (after - child_start) as u32;
588                        gaps.push(String::new());
589                        depth = 1;
590                    } else if depth == 1 {
591                        root_end_span = Some((before, after));
592                        depth = 0;
593                    } else {
594                        depth -= 1;
595                    }
596                }
597                Event::Text(e) if depth == 1 => {
598                    let text = e.xml_content().map_err(quick_xml::Error::from)?;
599                    if !text.trim().is_empty() {
600                        // text beside the children: the document is no stream
601                        return Ok(None);
602                    }
603                    gaps.last_mut().expect("a gap").push_str(&text);
604                }
605                Event::CData(_) | Event::GeneralRef(_) if depth == 1 => return Ok(None),
606                Event::Eof => break,
607                _ => {}
608            }
609            buf.clear();
610        }
611        let (Some((rs, re)), Some((es, ee)), Some(_)) = (root_span, root_end_span, root_tag) else {
612            return Ok(None);
613        };
614        if offsets.len() < 2 {
615            return Ok(None);
616        }
617        let covered: u64 = offsets.iter().map(|&(_, l)| l as u64).sum();
618        if covered * 2 < size {
619            return Ok(None);
620        }
621        let root_start = String::from_utf8_lossy(&bytes[rs..re]).into_owned();
622        let root_end = String::from_utf8_lossy(&bytes[es..ee]).into_owned();
623        // the prefix: the prologue, the document element, childless
624        let mut prefix_text = String::from_utf8_lossy(&bytes[..rs]).into_owned();
625        prefix_text.push_str(&root_start);
626        if !root_start.ends_with("/>") {
627            prefix_text.push_str(&root_end);
628        }
629        let prefix = XmlAdapter::parse(&prefix_text)?;
630        let anchor = *prefix
631            .children(prefix.root())
632            .first()
633            .ok_or(XmlError::NoRoot)?;
634        let file = quarb::source::Window::new(
635            std::fs::File::open(path).map_err(|e| quick_xml::Error::Io(std::sync::Arc::new(e)))?,
636            0,
637        );
638        Ok(Some(XmlStream {
639            size,
640            prefix,
641            anchor,
642            root_start,
643            root_end,
644            offsets,
645            tags,
646            tag_names,
647            gaps,
648            ids,
649            last: std::cell::RefCell::new(None),
650            reader: std::cell::RefCell::new((file, u32::MAX)),
651        }))
652    }
653
654    pub fn n_children(&self) -> usize {
655        self.offsets.len()
656    }
657
658    fn pack(i: u32, local: NodeId) -> NodeId {
659        NodeId(((i as u64 + 1) << CHILD_SHIFT) | local.0)
660    }
661
662    fn unpack(node: NodeId) -> Option<(u32, NodeId)> {
663        let i = (node.0 >> CHILD_SHIFT) as u32;
664        (i > 0).then(|| (i - 1, NodeId(node.0 & ((1u64 << CHILD_SHIFT) - 1))))
665    }
666
667    /// The child's own node in its arbor: the document element's
668    /// first child there.
669    const LOCAL_ROOT: NodeId = NodeId(2);
670
671    /// Child `i` parsed (or the one last parsed) in the document
672    /// element's wrapping, and `f` on its arbor.
673    fn with_child<T>(&self, i: u32, f: impl FnOnce(&XmlAdapter) -> T) -> Option<T> {
674        {
675            let last = self.last.borrow();
676            if let Some((k, a)) = &*last
677                && *k == i
678            {
679                return Some(f(a));
680            }
681        }
682        use std::io::{Read, Seek};
683        let &(offset, len) = self.offsets.get(i as usize)?;
684        let text = {
685            let mut r = self.reader.borrow_mut();
686            if r.1 != i {
687                r.0.seek(std::io::SeekFrom::Start(offset)).ok()?;
688            } else {
689                let here = r.0.stream_position().ok()?;
690                if here != offset {
691                    r.0.seek(std::io::SeekFrom::Start(offset)).ok()?;
692                }
693            }
694            let mut buf = vec![0u8; len as usize];
695            r.0.read_exact(&mut buf).ok()?;
696            r.1 = i + 1;
697            if let Some(&(next, _)) = self.offsets.get(i as usize + 1) {
698                let gap = next - (offset + len as u64);
699                if gap > 0 && gap < 1 << 16 {
700                    let mut skip = vec![0u8; gap as usize];
701                    r.0.read_exact(&mut skip).ok()?;
702                }
703            }
704            String::from_utf8(buf).ok()?
705        };
706        let wrapped = format!("{}{}{}", self.root_start, text, self.root_end);
707        let a = XmlAdapter::parse(&wrapped).ok()?;
708        let out = f(&a);
709        *self.last.borrow_mut() = Some((i, a));
710        Some(out)
711    }
712
713    /// The children as the plan reaches them: a child step, nothing
714    /// tested but the name.
715    fn children_plan(&self, from: NodeId, plan: &quarb::StepPlan<'_>) -> bool {
716        from == self.anchor
717            && plan.conjuncts.is_empty()
718            && plan.traits.is_empty()
719            && matches!(plan.axis, quarb::PlanAxis::Child)
720    }
721
722    fn matching(&self, name: Option<&str>) -> impl Iterator<Item = u32> + '_ {
723        let k = name
724            .and_then(|n| self.tag_names.iter().position(|t| t == n))
725            .map(|k| k as u32);
726        let named = name.is_some();
727        (0..self.offsets.len() as u32).filter(move |&i| !named || Some(self.tags[i as usize]) == k)
728    }
729
730    /// The node's locator, as the whole read spells it: a child among
731    /// same-tag siblings numbered when the tag repeats.
732    pub fn locator(&self, node: NodeId) -> String {
733        match Self::unpack(node) {
734            None => self.prefix.locator(node),
735            Some((i, local)) => {
736                let base = self.prefix.locator(self.anchor);
737                let tag = self.tags[i as usize];
738                let repeats = self.tags.iter().filter(|&&t| t == tag).count() > 1;
739                let nth = self.tags[..i as usize]
740                    .iter()
741                    .filter(|&&t| t == tag)
742                    .count()
743                    + 1;
744                let segment = if repeats {
745                    format!("{}[{nth}]", self.tag_names[tag as usize])
746                } else {
747                    self.tag_names[tag as usize].clone()
748                };
749                let inner = self.with_child(i, |a| a.locator(local)).unwrap_or_default();
750                // the arbor's locator: /root/child[/…]: the first two
751                // segments are the wrapping and the child itself
752                let rest: Vec<&str> = inner.trim_start_matches('/').splitn(3, '/').collect();
753                let tail = rest.get(2).map(|r| format!("/{r}")).unwrap_or_default();
754                format!("{base}/{segment}{tail}")
755            }
756        }
757    }
758}
759
760impl AstAdapter for XmlStream {
761    fn estimate(&self, _scope: &[&str], plan: &quarb::StepPlan<'_>) -> Option<quarb::Estimate> {
762        let n = self.matching(plan.name).count() as u64;
763        let nodes = match plan.limit {
764            Some(k) if self.children_plan(self.anchor, plan) => (n.min(k as u64), n.min(k as u64)),
765            _ => (n, n),
766        };
767        Some(quarb::Estimate {
768            nodes,
769            bytes: Some((self.size, self.size)),
770            requests: None,
771            latency: quarb::Latency::Local,
772            confidence: quarb::Confidence::Bound,
773        })
774    }
775
776    fn root(&self) -> NodeId {
777        self.prefix.root()
778    }
779
780    fn walks_for_references(&self) -> bool {
781        true
782    }
783
784    fn children(&self, node: NodeId) -> Vec<NodeId> {
785        match Self::unpack(node) {
786            Some((i, local)) => self
787                .with_child(i, |a| {
788                    a.children(local)
789                        .into_iter()
790                        .map(|c| Self::pack(i, c))
791                        .collect()
792                })
793                .unwrap_or_default(),
794            None if node == self.anchor => (0..self.offsets.len() as u32)
795                .map(|i| Self::pack(i, Self::LOCAL_ROOT))
796                .collect(),
797            None => self.prefix.children(node),
798        }
799    }
800
801    fn count(&self, from: NodeId, plan: &quarb::StepPlan<'_>) -> Option<usize> {
802        self.children_plan(from, plan)
803            .then(|| self.matching(plan.name).count())
804    }
805
806    fn select(&self, from: NodeId, plan: &quarb::StepPlan<'_>) -> Option<quarb::Selection> {
807        let k = plan.limit?;
808        if !self.children_plan(from, plan) {
809            return None;
810        }
811        Some(quarb::Selection {
812            nodes: self
813                .matching(plan.name)
814                .take(k)
815                .map(|i| (Self::pack(i, Self::LOCAL_ROOT), 1))
816                .collect(),
817            applied: Vec::new(),
818        })
819    }
820
821    fn name(&self, node: NodeId) -> Option<String> {
822        match Self::unpack(node) {
823            Some((i, local)) if local == Self::LOCAL_ROOT => {
824                Some(self.tag_names[self.tags[i as usize] as usize].clone())
825            }
826            Some((i, local)) => self.with_child(i, |a| a.name(local)).flatten(),
827            None => self.prefix.name(node),
828        }
829    }
830
831    fn traits(&self, node: NodeId) -> Vec<String> {
832        match Self::unpack(node) {
833            Some((i, local)) => self.with_child(i, |a| a.traits(local)).unwrap_or_default(),
834            None => self.prefix.traits(node),
835        }
836    }
837
838    fn parent(&self, node: NodeId) -> Option<NodeId> {
839        match Self::unpack(node) {
840            Some((_, local)) if local == Self::LOCAL_ROOT => Some(self.anchor),
841            Some((i, local)) => self
842                .with_child(i, |a| a.parent(local).map(|p| Self::pack(i, p)))
843                .flatten(),
844            None => self.prefix.parent(node),
845        }
846    }
847
848    fn ref_property(&self, node: NodeId) -> Option<String> {
849        match Self::unpack(node) {
850            Some((i, local)) => self.with_child(i, |a| a.ref_property(local)).flatten(),
851            None => self.prefix.ref_property(node),
852        }
853    }
854
855    fn property_names(&self, node: NodeId) -> Vec<String> {
856        match Self::unpack(node) {
857            Some((i, local)) => self
858                .with_child(i, |a| a.property_names(local))
859                .unwrap_or_default(),
860            None => self.prefix.property_names(node),
861        }
862    }
863
864    fn can_refer_to(&self, _source: NodeId, _target: NodeId) -> Option<bool> {
865        Some(true)
866    }
867
868    fn property(&self, node: NodeId, name: &str) -> Option<Value> {
869        match Self::unpack(node) {
870            Some((i, local)) => self.with_child(i, |a| a.property(local, name)).flatten(),
871            None => self.prefix.property(node, name),
872        }
873    }
874
875    fn default_value(&self, node: NodeId) -> Option<Value> {
876        match Self::unpack(node) {
877            Some((i, local)) => self.with_child(i, |a| a.default_value(local)).flatten(),
878            // the document element's text is its children's, in order,
879            // with its own whitespace between; the document node's too,
880            // as the text flows up in the whole read
881            None if node == self.anchor || node == self.prefix.root() => {
882                let mut text = String::new();
883                for i in 0..self.offsets.len() as u32 {
884                    text.push_str(&self.gaps[i as usize]);
885                    if let Some(Some(Value::Str(t))) =
886                        self.with_child(i, |a| a.default_value(Self::LOCAL_ROOT))
887                    {
888                        text.push_str(&t);
889                    }
890                }
891                if let Some(tail) = self.gaps.get(self.offsets.len()) {
892                    text.push_str(tail);
893                }
894                Some(Value::Str(text))
895            }
896            None => self.prefix.default_value(node),
897        }
898    }
899
900    fn metadata_catalogue(&self) -> &'static [&'static str] {
901        &["tag", "local-name", "ns-prefix", "n-attrs", "texts"]
902    }
903
904    fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
905        match Self::unpack(node) {
906            Some((i, local)) => self.with_child(i, |a| a.metadata(local, key)).flatten(),
907            // the document element's own text is what stands between
908            // its children
909            None if key == "texts" && node == self.anchor => {
910                let runs: Vec<Value> = self
911                    .gaps
912                    .iter()
913                    .filter_map(|g| collapsed(g))
914                    .map(Value::Str)
915                    .collect();
916                (!runs.is_empty()).then(|| Value::list(runs))
917            }
918            None => self.prefix.metadata(node, key),
919        }
920    }
921
922    fn resolve(&self, node: NodeId, property: &str, hint: Option<&str>) -> Option<NodeId> {
923        let value = self.property(node, property)?;
924        let Value::Str(s) = value else {
925            return None;
926        };
927        let target = s.strip_prefix('#').unwrap_or(&s).to_string();
928        // in the same child first, as the whole read finds it
929        if let Some((i, local)) = Self::unpack(node)
930            && let Some(Some(r)) = self.with_child(i, |a| a.resolve(local, property, hint))
931        {
932            return Some(Self::pack(i, r));
933        }
934        let j = *self.ids.get(&target)?;
935        self.with_child(j, |a| a.node_by_id(&target).map(|r| Self::pack(j, r)))
936            .flatten()
937    }
938}
939
940#[cfg(test)]
941mod declared_tests {
942    #[test]
943    fn prologue_declaration() {
944        assert_eq!(
945            super::declared_encoding(b"<?xml version='1.0' encoding = 'Windows-1251' ?><a/>"),
946            Some("Windows-1251".into())
947        );
948        assert_eq!(
949            super::declared_encoding(b"<?xml version=\"1.0\"?><a/>"),
950            None
951        );
952        assert_eq!(super::declared_encoding(b"<a encoding=\"x\"/>"), None);
953        assert_eq!(
954            super::declared_encoding(b"<?xml-stylesheet href=\"a.xsl\" encoding=\"koi8-r\"?><r/>"),
955            None
956        );
957        assert_eq!(
958            super::declared_encoding(b"\xef\xbb\xbf<?xml encoding=\"utf-8\"?>"),
959            None
960        );
961    }
962}
963
964#[cfg(test)]
965mod stream_tests {
966    //! The document with one repeated child streamed reads as the
967    //! whole file does, node for node.
968    use super::*;
969
970    const DOC: &str = "<?xml version=\"1.0\"?>\n<dictionary xmlns:x=\"urn:x\" lang=\"grc\">\n  <entry id=\"e1\" x:n=\"1\"><form>λόγος</form><sense>word</sense><see ref=\"e3\"/></entry>\n  <entry id=\"e2\"><form>μῆνις</form><sense n=\"a\">wrath &amp; rage</sense></entry>\n  <note id=\"n1\">a note</note>\n  <entry id=\"e3\"><form>ἀοιδός</form><sense>singer</sense><see ref=\"#e1\"/></entry>\n</dictionary>\n";
971
972    fn file(name: &str, text: &str) -> std::path::PathBuf {
973        let dir = std::env::temp_dir().join(format!("quarb-xml-stream-{}", std::process::id()));
974        std::fs::create_dir_all(&dir).unwrap();
975        let p = dir.join(name);
976        std::fs::write(&p, text).unwrap();
977        p
978    }
979
980    fn walk(s: &XmlStream, sn: NodeId, w: &XmlAdapter, wn: NodeId, depth: usize) {
981        assert!(depth < 10);
982        assert_eq!(s.name(sn), w.name(wn), "name at {}", w.locator(wn));
983        assert_eq!(s.traits(sn), w.traits(wn), "traits at {}", w.locator(wn));
984        assert_eq!(
985            s.property_names(sn),
986            w.property_names(wn),
987            "attrs at {}",
988            w.locator(wn)
989        );
990        for a in w.property_names(wn) {
991            assert_eq!(
992                s.property(sn, &a),
993                w.property(wn, &a),
994                "{a} at {}",
995                w.locator(wn)
996            );
997        }
998        assert_eq!(
999            s.default_value(sn),
1000            w.default_value(wn),
1001            "text at {}",
1002            w.locator(wn)
1003        );
1004        assert_eq!(s.locator(sn), w.locator(wn), "locator");
1005        for k in ["tag", "local-name", "ns-prefix", "n-attrs", "texts"] {
1006            assert_eq!(
1007                s.metadata(sn, k),
1008                w.metadata(wn, k),
1009                "{k} at {}",
1010                w.locator(wn)
1011            );
1012        }
1013        let sc = s.children(sn);
1014        let wc = w.children(wn);
1015        assert_eq!(sc.len(), wc.len(), "children at {}", w.locator(wn));
1016        for (a, b) in sc.iter().zip(wc.iter()) {
1017            assert_eq!(s.parent(*a), Some(sn), "parent at {}", w.locator(*b));
1018            walk(s, *a, w, *b, depth + 1);
1019        }
1020    }
1021
1022    #[test]
1023    fn the_children_read_as_the_whole_file_does() {
1024        let p = file("dict.xml", DOC);
1025        let s = XmlStream::open(&p)
1026            .unwrap()
1027            .expect("a document worth streaming");
1028        assert_eq!(s.n_children(), 4);
1029        let w = XmlAdapter::parse(DOC).unwrap();
1030        walk(&s, s.root(), &w, w.root(), 0);
1031        // the plan hooks, by name and bare
1032        let dict = s.children(s.root())[0];
1033        let mut plan = quarb::StepPlan {
1034            traits: Vec::new(),
1035            cap: quarb::Cap {
1036                nodes: None,
1037                bytes: None,
1038            },
1039            axis: quarb::PlanAxis::Child,
1040            name: Some("entry"),
1041            conjuncts: Vec::new(),
1042            limit: Some(2),
1043            order: None,
1044        };
1045        assert_eq!(s.count(dict, &plan), Some(3));
1046        assert_eq!(s.select(dict, &plan).map(|sel| sel.nodes.len()), Some(2));
1047        plan.name = None;
1048        assert_eq!(s.count(dict, &plan), Some(4));
1049        // a reference across children, bare and with the fragment sigil
1050        let e1 = s.children(dict)[0];
1051        let see = s.children(e1)[2];
1052        let target = s.resolve(see, "ref", None).expect("resolves");
1053        assert_eq!(s.property(target, "id"), Some(Value::Str("e3".into())));
1054        let e3 = s.children(dict)[3];
1055        let back = s.resolve(s.children(e3)[2], "ref", None).expect("resolves");
1056        assert_eq!(s.property(back, "id"), Some(Value::Str("e1".into())));
1057    }
1058
1059    #[test]
1060    fn a_document_with_text_beside_its_children_reads_whole() {
1061        let p = file("mixed.xml", "<r>text <a>1</a> more <a>2</a></r>");
1062        assert!(XmlStream::open(&p).unwrap().is_none());
1063        let p = file(
1064            "one.xml",
1065            "<r><a>only one child, under half the file by its text? no, over</a></r>",
1066        );
1067        assert!(XmlStream::open(&p).unwrap().is_none());
1068    }
1069}