f-office-xml 0.2.4

Minimal read-only XML tree for Office Open XML and SVG parts.
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
//! Single-pass streaming scanner for WordprocessingML `<w:body>` top-level child blocks.
//!
//! Locates the exact UTF-8 byte ranges of direct `<w:body>` children (`<w:p>`, `<w:tbl>`,
//! `<w:sdt>`, `<w:sectPr>`, `<w:bookmarkStart>`, etc.) without building a full-document XML tree,
//! enabling callers to parse and drop one block at a time while preserving exact part byte spans.

use std::ops::Range;

use quick_xml::XmlVersion;
use quick_xml::events::{BytesStart, Event};
use quick_xml::name::ResolveResult;
use quick_xml::reader::NsReader;

use crate::{Error, Limits, UTF8_MARK, declared_encoding};

/// Index of a WordprocessingML main document part produced by [`scan_body_children`].
#[derive(Clone, Debug)]
pub struct StreamedBody {
    /// Namespace declarations in scope inside `<w:body>` (nearest declaration first: `<w:body>`
    /// overrides `<w:document>`).
    pub in_scope: Vec<(String, String)>,
    /// Namespace declarations in scope directly on `<w:document>` (for parsing `<w:background>`).
    pub doc_in_scope: Vec<(String, String)>,
    /// Byte range of `<w:background>` directly under `<w:document>`, if present.
    pub background: Option<Range<usize>>,
    /// Exact byte ranges of every direct child element of `<w:body>` in document order.
    pub children: Vec<Range<usize>>,
    /// `true` when any tracked-change element was encountered inside the part.
    pub has_revisions: bool,
    /// `true` when a comment marker, field instruction, or alternate-content block at body level
    /// requires cross-paragraph whole-document analysis.
    pub has_cross_block_features: bool,
}

/// Scans `bytes` in a single streaming pass without constructing an XML DOM and returns the exact
/// byte ranges of every direct child element of `<w:body>` (when `bytes` is UTF-8 and contains a
/// `<w:document>` / `<w:body>` in one of `w_namespaces`).
///
/// Any direct `<w:body>` child whose local name is in `body_wrappers` (such as `customXml`, `sdt`,
/// or `AlternateContent`) sets [`StreamedBody::has_cross_block_features`] so callers can route the
/// document to the tree reader.
///
/// Returns `Ok(None)` when the document is not UTF-8 or does not match the standard
/// `<w:document><w:body>...</w:body></w:document>` layout (callers fall back to [`crate::Document::parse_with_aliases`]).
///
/// # Errors
///
/// Returns [`Error::DocType`], [`Error::TooDeep`], [`Error::TooManyNodes`], [`Error::TooLarge`],
/// or [`Error::Syntax`] if the XML violates limits or is malformed.
pub fn scan_body_children(
    bytes: &[u8],
    w_namespaces: &[&str],
    body_wrappers: &[&str],
    limits: &Limits,
) -> Result<Option<StreamedBody>, Error> {
    u32::try_from(bytes.len()).map_err(|_| Error::TooLarge)?;
    if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
        return Ok(None);
    }
    let skipped = if bytes.starts_with(&UTF8_MARK) {
        UTF8_MARK.len()
    } else {
        0
    };
    let mut reader = NsReader::from_reader(bytes);
    reader.config_mut().check_end_names = true;
    let mut state = ScanState::new(w_namespaces, body_wrappers, limits, skipped);
    let mut buf = Vec::new();
    loop {
        buf.clear();
        let start = state.position(&reader)?;
        let (resolved, event) = reader
            .read_resolved_event_into(&mut buf)
            .map_err(|error| Error::Syntax(error.to_string()))?;
        let is_w = state.is_w(&resolved);
        let end = state.position(&reader)?;
        match event {
            Event::Eof => break,
            Event::DocType(_) => return Err(Error::DocType),
            Event::Decl(decl) => {
                if declared_encoding(&decl).is_some() {
                    return Ok(None);
                }
            }
            Event::Start(tag) => state.on_start(&tag, is_w, start, end, false)?,
            Event::Empty(tag) => state.on_start(&tag, is_w, start, end, true)?,
            Event::End(_) => state.on_end(end),
            Event::Text(_)
            | Event::CData(_)
            | Event::GeneralRef(_)
            | Event::Comment(_)
            | Event::PI(_) => {}
        }
    }
    if state.depth != 0 {
        return Err(Error::Syntax("unclosed element".to_owned()));
    }
    Ok(state.finish())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ScanPhase {
    BeforeDocument,
    InDocument,
    InBody,
    AfterBody,
}

struct ScanState<'a> {
    w_namespaces: &'a [&'a str],
    body_wrappers: &'a [&'a str],
    limits: &'a Limits,
    skipped: usize,
    depth: usize,
    nodes: usize,
    phase: ScanPhase,
    doc_decls: Vec<(String, String)>,
    body_decls: Vec<(String, String)>,
    background_start: Option<usize>,
    background: Option<Range<usize>>,
    child_start: Option<usize>,
    children: Vec<Range<usize>>,
    has_revisions: bool,
    has_cross_block_features: bool,
}

impl<'a> ScanState<'a> {
    fn new(
        w_namespaces: &'a [&'a str],
        body_wrappers: &'a [&'a str],
        limits: &'a Limits,
        skipped: usize,
    ) -> Self {
        Self {
            w_namespaces,
            body_wrappers,
            limits,
            skipped,
            depth: 0,
            nodes: 0,
            phase: ScanPhase::BeforeDocument,
            doc_decls: Vec::new(),
            body_decls: Vec::new(),
            background_start: None,
            background: None,
            child_start: None,
            children: Vec::new(),
            has_revisions: false,
            has_cross_block_features: false,
        }
    }

    fn position(&self, reader: &NsReader<&[u8]>) -> Result<usize, Error> {
        let pos = usize::try_from(reader.buffer_position())
            .map_err(|_| Error::TooLarge)?
            .saturating_add(self.skipped);
        Ok(pos)
    }

    fn is_w(&self, resolved: &ResolveResult<'_>) -> bool {
        matches!(resolved, ResolveResult::Bound(ns) if self.w_namespaces.contains(&ns.as_ref()))
    }

    fn on_start(
        &mut self,
        tag: &BytesStart<'_>,
        is_w: bool,
        start: usize,
        end: usize,
        empty: bool,
    ) -> Result<(), Error> {
        self.nodes += 1;
        if self.nodes > self.limits.max_nodes {
            return Err(Error::TooManyNodes);
        }
        let next_depth = self.depth + 1;
        if !empty && next_depth > self.limits.max_depth {
            return Err(Error::TooDeep);
        }
        let local = tag.local_name();
        let local_str = local.as_ref();
        match (next_depth, self.phase) {
            (1, ScanPhase::BeforeDocument) if is_w && local_str == "document" => {
                self.doc_decls = collect_xmlns(tag)?;
                if !empty {
                    self.phase = ScanPhase::InDocument;
                }
            }
            (2, ScanPhase::InDocument) if is_w => {
                self.on_document_child(tag, local_str, start, end, empty)?;
            }
            (3, ScanPhase::InBody) => {
                self.on_body_child(local_str, start, end, empty);
            }
            _ => {}
        }
        if is_w {
            self.flag_features(local_str);
        }
        if !empty {
            self.depth = next_depth;
        }
        Ok(())
    }

    fn on_document_child(
        &mut self,
        tag: &BytesStart<'_>,
        local: &str,
        start: usize,
        end: usize,
        empty: bool,
    ) -> Result<(), Error> {
        if local == "background" && self.background.is_none() {
            if empty {
                self.background = Some(start..end);
            } else {
                self.background_start = Some(start);
            }
        } else if local == "body" {
            self.body_decls = collect_xmlns(tag)?;
            self.phase = if empty {
                ScanPhase::AfterBody
            } else {
                ScanPhase::InBody
            };
        }
        Ok(())
    }

    fn on_body_child(&mut self, local: &str, start: usize, end: usize, empty: bool) {
        if empty {
            self.children.push(start..end);
        } else {
            self.child_start = Some(start);
        }
        if self.body_wrappers.contains(&local) {
            self.has_cross_block_features = true;
        }
    }

    fn flag_features(&mut self, local: &str) {
        if matches!(
            local,
            "del"
                | "ins"
                | "moveFrom"
                | "moveTo"
                | "pPrChange"
                | "rPrChange"
                | "tblPrChange"
                | "trPrChange"
                | "tcPrChange"
                | "sectPrChange"
                | "customXmlDelRangeStart"
                | "customXmlInsRangeStart"
                | "customXmlMoveFromRangeStart"
                | "customXmlMoveToRangeStart"
        ) {
            self.has_revisions = true;
        } else if matches!(
            local,
            "commentRangeStart"
                | "commentRangeEnd"
                | "commentReference"
                | "fldSimple"
                | "instrText"
        ) {
            self.has_cross_block_features = true;
        }
    }

    fn on_end(&mut self, end: usize) {
        match (self.depth, self.phase) {
            (3, ScanPhase::InBody) => {
                if let Some(start) = self.child_start.take() {
                    self.children.push(start..end);
                }
            }
            (2, ScanPhase::InBody) => {
                self.phase = ScanPhase::AfterBody;
            }
            (2, ScanPhase::InDocument) => {
                if let Some(start) = self.background_start.take() {
                    self.background = Some(start..end);
                }
            }
            _ => {}
        }
        self.depth = self.depth.saturating_sub(1);
    }

    fn finish(self) -> Option<StreamedBody> {
        if !matches!(self.phase, ScanPhase::InBody | ScanPhase::AfterBody) {
            return None;
        }
        let mut in_scope = self.body_decls;
        for (prefix, uri) in &self.doc_decls {
            if in_scope.iter().all(|(known, _)| known != prefix) {
                in_scope.push((prefix.clone(), uri.clone()));
            }
        }
        Some(StreamedBody {
            in_scope,
            doc_in_scope: self.doc_decls,
            background: self.background,
            children: self.children,
            has_revisions: self.has_revisions,
            has_cross_block_features: self.has_cross_block_features,
        })
    }
}

/// Collects `xmlns` / `xmlns:prefix` declarations directly on `tag`.
fn collect_xmlns(tag: &BytesStart<'_>) -> Result<Vec<(String, String)>, Error> {
    let mut decls = Vec::new();
    for attr in tag.attributes() {
        let attr = attr.map_err(|error| Error::Syntax(error.to_string()))?;
        let key = attr.key;
        let prefix = match key.prefix() {
            Some(p) if p.as_ref() == "xmlns" => key.local_name().as_ref().to_owned(),
            None if key.local_name().as_ref() == "xmlns" => String::new(),
            _ => continue,
        };
        let value = attr
            .normalized_value(XmlVersion::Implicit1_0)
            .map_err(|error| Error::Syntax(error.to_string()))?
            .into_owned();
        if decls.iter().all(|(known, _)| known != &prefix) {
            decls.push((prefix, value));
        }
    }
    Ok(decls)
}

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

    const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

    const WRAPPERS: [&str; 3] = ["customXml", "sdt", "AlternateContent"];

    #[test]
    fn scans_body_children_with_exact_byte_spans_and_background() {
        let xml = format!(
            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>"#
        );
        let streamed = scan_body_children(xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
            .unwrap()
            .unwrap();
        assert_eq!(
            (
                streamed.has_revisions,
                streamed.has_cross_block_features,
                streamed.children.len(),
                &xml[streamed.background.unwrap()],
                &xml[streamed.children[0].clone()],
                &xml[streamed.children[1].clone()],
                &xml[streamed.children[2].clone()],
            ),
            (
                false,
                false,
                3,
                r#"<w:background w:color="FFEEAA"/>"#,
                "<w:p><w:r><w:t>One</w:t></w:r></w:p>",
                "<w:tbl/>",
                "<w:sectPr/>",
            )
        );

        // Parsing child 0 with base_offset matches full-document Document::span byte-for-byte!
        let full = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let full_body = full.child(full.root().unwrap(), W, "body").unwrap();
        let full_p = full.child(full_body, W, "p").unwrap();
        let range = streamed.children[0].clone();
        let frag = Document::parse_fragment_with_aliases_at(
            &xml.as_bytes()[range.clone()],
            &streamed.in_scope,
            &[],
            range.start as u64,
            &Limits::default(),
        )
        .unwrap();
        let frag_p = frag.nodes()[0];
        assert_eq!(
            frag.document().span(frag_p).unwrap(),
            full.span(full_p).unwrap()
        );
    }

    #[test]
    fn flags_revisions_and_cross_block_features() {
        let rev_xml = format!(
            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>"#
        );
        let streamed = scan_body_children(rev_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
            .unwrap()
            .unwrap();
        assert!(streamed.has_revisions);

        let toc_xml = format!(
            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>"#
        );
        let streamed = scan_body_children(toc_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
            .unwrap()
            .unwrap();
        assert!(streamed.has_cross_block_features);

        let custom_xml = format!(
            r#"<w:document xmlns:w="{W}"><w:body><w:customXml><w:p><w:r><w:t>inside</w:t></w:r></w:p></w:customXml></w:body></w:document>"#
        );
        let streamed =
            scan_body_children(custom_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
                .unwrap()
                .unwrap();
        assert!(streamed.has_cross_block_features);
    }
}