Skip to main content

f_office_xml/
stream.rs

1//! Single-pass streaming scanner for WordprocessingML `<w:body>` top-level child blocks.
2//!
3//! Locates the exact UTF-8 byte ranges of direct `<w:body>` children (`<w:p>`, `<w:tbl>`,
4//! `<w:sdt>`, `<w:sectPr>`, `<w:bookmarkStart>`, etc.) without building a full-document XML tree,
5//! enabling callers to parse and drop one block at a time while preserving exact part byte spans.
6
7use std::ops::Range;
8
9use quick_xml::XmlVersion;
10use quick_xml::events::{BytesStart, Event};
11use quick_xml::name::ResolveResult;
12use quick_xml::reader::NsReader;
13
14use crate::{Error, Limits, UTF8_MARK, declared_encoding};
15
16/// Index of a WordprocessingML main document part produced by [`scan_body_children`].
17#[derive(Clone, Debug)]
18pub struct StreamedBody {
19    /// Namespace declarations in scope inside `<w:body>` (nearest declaration first: `<w:body>`
20    /// overrides `<w:document>`).
21    pub in_scope: Vec<(String, String)>,
22    /// Namespace declarations in scope directly on `<w:document>` (for parsing `<w:background>`).
23    pub doc_in_scope: Vec<(String, String)>,
24    /// Byte range of `<w:background>` directly under `<w:document>`, if present.
25    pub background: Option<Range<usize>>,
26    /// Exact byte ranges of every direct child element of `<w:body>` in document order.
27    pub children: Vec<Range<usize>>,
28    /// `true` when any tracked-change element was encountered inside the part.
29    pub has_revisions: bool,
30    /// `true` when a comment marker, field instruction, or alternate-content block at body level
31    /// requires cross-paragraph whole-document analysis.
32    pub has_cross_block_features: bool,
33}
34
35/// Scans `bytes` in a single streaming pass without constructing an XML DOM and returns the exact
36/// byte ranges of every direct child element of `<w:body>` (when `bytes` is UTF-8 and contains a
37/// `<w:document>` / `<w:body>` in one of `w_namespaces`).
38///
39/// Returns `Ok(None)` when the document is not UTF-8 or does not match the standard
40/// `<w:document><w:body>...</w:body></w:document>` layout (callers fall back to [`crate::Document::parse_with_aliases`]).
41///
42/// # Errors
43///
44/// Returns [`Error::DocType`], [`Error::TooDeep`], [`Error::TooManyNodes`], [`Error::TooLarge`],
45/// or [`Error::Syntax`] if the XML violates limits or is malformed.
46pub fn scan_body_children(
47    bytes: &[u8],
48    w_namespaces: &[&str],
49    limits: &Limits,
50) -> Result<Option<StreamedBody>, Error> {
51    u32::try_from(bytes.len()).map_err(|_| Error::TooLarge)?;
52    if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
53        return Ok(None);
54    }
55    let skipped = if bytes.starts_with(&UTF8_MARK) {
56        UTF8_MARK.len()
57    } else {
58        0
59    };
60    let mut reader = NsReader::from_reader(bytes);
61    reader.config_mut().check_end_names = true;
62    let mut state = ScanState::new(w_namespaces, limits, skipped);
63    let mut buf = Vec::new();
64    loop {
65        buf.clear();
66        let start = state.position(&reader)?;
67        let (resolved, event) = reader
68            .read_resolved_event_into(&mut buf)
69            .map_err(|error| Error::Syntax(error.to_string()))?;
70        let is_w = state.is_w(&resolved);
71        let end = state.position(&reader)?;
72        match event {
73            Event::Eof => break,
74            Event::DocType(_) => return Err(Error::DocType),
75            Event::Decl(decl) => {
76                if declared_encoding(&decl).is_some() {
77                    return Ok(None);
78                }
79            }
80            Event::Start(tag) => state.on_start(&tag, is_w, start, end, false)?,
81            Event::Empty(tag) => state.on_start(&tag, is_w, start, end, true)?,
82            Event::End(_) => state.on_end(end),
83            Event::Text(_)
84            | Event::CData(_)
85            | Event::GeneralRef(_)
86            | Event::Comment(_)
87            | Event::PI(_) => {}
88        }
89    }
90    if state.depth != 0 {
91        return Err(Error::Syntax("unclosed element".to_owned()));
92    }
93    Ok(state.finish())
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97enum ScanPhase {
98    BeforeDocument,
99    InDocument,
100    InBody,
101    AfterBody,
102}
103
104struct ScanState<'a> {
105    w_namespaces: &'a [&'a str],
106    limits: &'a Limits,
107    skipped: usize,
108    depth: usize,
109    nodes: usize,
110    phase: ScanPhase,
111    doc_decls: Vec<(String, String)>,
112    body_decls: Vec<(String, String)>,
113    background_start: Option<usize>,
114    background: Option<Range<usize>>,
115    child_start: Option<usize>,
116    children: Vec<Range<usize>>,
117    has_revisions: bool,
118    has_cross_block_features: bool,
119}
120
121impl<'a> ScanState<'a> {
122    fn new(w_namespaces: &'a [&'a str], limits: &'a Limits, skipped: usize) -> Self {
123        Self {
124            w_namespaces,
125            limits,
126            skipped,
127            depth: 0,
128            nodes: 0,
129            phase: ScanPhase::BeforeDocument,
130            doc_decls: Vec::new(),
131            body_decls: Vec::new(),
132            background_start: None,
133            background: None,
134            child_start: None,
135            children: Vec::new(),
136            has_revisions: false,
137            has_cross_block_features: false,
138        }
139    }
140
141    fn position(&self, reader: &NsReader<&[u8]>) -> Result<usize, Error> {
142        let pos = usize::try_from(reader.buffer_position())
143            .map_err(|_| Error::TooLarge)?
144            .saturating_add(self.skipped);
145        Ok(pos)
146    }
147
148    fn is_w(&self, resolved: &ResolveResult<'_>) -> bool {
149        matches!(resolved, ResolveResult::Bound(ns) if self.w_namespaces.contains(&ns.as_ref()))
150    }
151
152    fn on_start(
153        &mut self,
154        tag: &BytesStart<'_>,
155        is_w: bool,
156        start: usize,
157        end: usize,
158        empty: bool,
159    ) -> Result<(), Error> {
160        self.nodes += 1;
161        if self.nodes > self.limits.max_nodes {
162            return Err(Error::TooManyNodes);
163        }
164        let next_depth = self.depth + 1;
165        if !empty && next_depth > self.limits.max_depth {
166            return Err(Error::TooDeep);
167        }
168        let local = tag.local_name();
169        let local_str = local.as_ref();
170        match (next_depth, self.phase) {
171            (1, ScanPhase::BeforeDocument) if is_w && local_str == "document" => {
172                self.doc_decls = collect_xmlns(tag)?;
173                if !empty {
174                    self.phase = ScanPhase::InDocument;
175                }
176            }
177            (2, ScanPhase::InDocument) if is_w => {
178                self.on_document_child(tag, local_str, start, end, empty)?;
179            }
180            (3, ScanPhase::InBody) => {
181                self.on_body_child(local_str, start, end, empty);
182            }
183            _ => {}
184        }
185        if is_w {
186            self.flag_features(local_str);
187        }
188        if !empty {
189            self.depth = next_depth;
190        }
191        Ok(())
192    }
193
194    fn on_document_child(
195        &mut self,
196        tag: &BytesStart<'_>,
197        local: &str,
198        start: usize,
199        end: usize,
200        empty: bool,
201    ) -> Result<(), Error> {
202        if local == "background" && self.background.is_none() {
203            if empty {
204                self.background = Some(start..end);
205            } else {
206                self.background_start = Some(start);
207            }
208        } else if local == "body" {
209            self.body_decls = collect_xmlns(tag)?;
210            self.phase = if empty {
211                ScanPhase::AfterBody
212            } else {
213                ScanPhase::InBody
214            };
215        }
216        Ok(())
217    }
218
219    fn on_body_child(&mut self, local: &str, start: usize, end: usize, empty: bool) {
220        if empty {
221            self.children.push(start..end);
222        } else {
223            self.child_start = Some(start);
224        }
225        if local == "AlternateContent" || local == "sdt" {
226            self.has_cross_block_features = true;
227        }
228    }
229
230    fn flag_features(&mut self, local: &str) {
231        if matches!(
232            local,
233            "del"
234                | "ins"
235                | "moveFrom"
236                | "moveTo"
237                | "pPrChange"
238                | "rPrChange"
239                | "tblPrChange"
240                | "trPrChange"
241                | "tcPrChange"
242                | "sectPrChange"
243                | "customXmlDelRangeStart"
244                | "customXmlInsRangeStart"
245                | "customXmlMoveFromRangeStart"
246                | "customXmlMoveToRangeStart"
247        ) {
248            self.has_revisions = true;
249        } else if matches!(
250            local,
251            "commentRangeStart"
252                | "commentRangeEnd"
253                | "commentReference"
254                | "fldSimple"
255                | "instrText"
256        ) {
257            self.has_cross_block_features = true;
258        }
259    }
260
261    fn on_end(&mut self, end: usize) {
262        match (self.depth, self.phase) {
263            (3, ScanPhase::InBody) => {
264                if let Some(start) = self.child_start.take() {
265                    self.children.push(start..end);
266                }
267            }
268            (2, ScanPhase::InBody) => {
269                self.phase = ScanPhase::AfterBody;
270            }
271            (2, ScanPhase::InDocument) => {
272                if let Some(start) = self.background_start.take() {
273                    self.background = Some(start..end);
274                }
275            }
276            _ => {}
277        }
278        self.depth = self.depth.saturating_sub(1);
279    }
280
281    fn finish(self) -> Option<StreamedBody> {
282        if !matches!(self.phase, ScanPhase::InBody | ScanPhase::AfterBody) {
283            return None;
284        }
285        let mut in_scope = self.body_decls;
286        for (prefix, uri) in &self.doc_decls {
287            if in_scope.iter().all(|(known, _)| known != prefix) {
288                in_scope.push((prefix.clone(), uri.clone()));
289            }
290        }
291        Some(StreamedBody {
292            in_scope,
293            doc_in_scope: self.doc_decls,
294            background: self.background,
295            children: self.children,
296            has_revisions: self.has_revisions,
297            has_cross_block_features: self.has_cross_block_features,
298        })
299    }
300}
301
302/// Collects `xmlns` / `xmlns:prefix` declarations directly on `tag`.
303fn collect_xmlns(tag: &BytesStart<'_>) -> Result<Vec<(String, String)>, Error> {
304    let mut decls = Vec::new();
305    for attr in tag.attributes() {
306        let attr = attr.map_err(|error| Error::Syntax(error.to_string()))?;
307        let key = attr.key;
308        let prefix = match key.prefix() {
309            Some(p) if p.as_ref() == "xmlns" => key.local_name().as_ref().to_owned(),
310            None if key.local_name().as_ref() == "xmlns" => String::new(),
311            _ => continue,
312        };
313        let value = attr
314            .normalized_value(XmlVersion::Implicit1_0)
315            .map_err(|error| Error::Syntax(error.to_string()))?
316            .into_owned();
317        if decls.iter().all(|(known, _)| known != &prefix) {
318            decls.push((prefix, value));
319        }
320    }
321    Ok(decls)
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use crate::Document;
328
329    const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
330
331    #[test]
332    fn scans_body_children_with_exact_byte_spans_and_background() {
333        let xml = format!(
334            r#"<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="{W}"><w:background w:color="FFEEAA"/><w:body><w:p><w:r><w:t>One</w:t></w:r></w:p><w:tbl/><w:sectPr/></w:body></w:document>"#
335        );
336        let streamed = scan_body_children(xml.as_bytes(), &[W], &Limits::default())
337            .unwrap()
338            .unwrap();
339        assert_eq!(
340            (
341                streamed.has_revisions,
342                streamed.has_cross_block_features,
343                streamed.children.len(),
344                &xml[streamed.background.unwrap()],
345                &xml[streamed.children[0].clone()],
346                &xml[streamed.children[1].clone()],
347                &xml[streamed.children[2].clone()],
348            ),
349            (
350                false,
351                false,
352                3,
353                r#"<w:background w:color="FFEEAA"/>"#,
354                "<w:p><w:r><w:t>One</w:t></w:r></w:p>",
355                "<w:tbl/>",
356                "<w:sectPr/>",
357            )
358        );
359
360        // Parsing child 0 with base_offset matches full-document Document::span byte-for-byte!
361        let full = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
362        let full_body = full.child(full.root().unwrap(), W, "body").unwrap();
363        let full_p = full.child(full_body, W, "p").unwrap();
364        let range = streamed.children[0].clone();
365        let frag = Document::parse_fragment_with_aliases_at(
366            &xml.as_bytes()[range.clone()],
367            &streamed.in_scope,
368            &[],
369            range.start as u64,
370            &Limits::default(),
371        )
372        .unwrap();
373        let frag_p = frag.nodes()[0];
374        assert_eq!(
375            frag.document().span(frag_p).unwrap(),
376            full.span(full_p).unwrap()
377        );
378    }
379
380    #[test]
381    fn flags_revisions_and_cross_block_features() {
382        let rev_xml = format!(
383            r#"<w:document xmlns:w="{W}"><w:body><w:p><w:ins><w:r><w:t>hi</w:t></w:r></w:ins></w:p></w:body></w:document>"#
384        );
385        let streamed = scan_body_children(rev_xml.as_bytes(), &[W], &Limits::default())
386            .unwrap()
387            .unwrap();
388        assert!(streamed.has_revisions);
389
390        let toc_xml = format!(
391            r#"<w:document xmlns:w="{W}"><w:body><w:p><w:r><w:instrText>TOC</w:instrText></w:r></w:p></w:body></w:document>"#
392        );
393        let streamed = scan_body_children(toc_xml.as_bytes(), &[W], &Limits::default())
394            .unwrap()
395            .unwrap();
396        assert!(streamed.has_cross_block_features);
397    }
398}