f-office-xml 0.2.3

Minimal read-only XML tree for Office Open XML and SVG parts.
Documentation
//! 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`).
///
/// 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],
    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, 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],
    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], limits: &'a Limits, skipped: usize) -> Self {
        Self {
            w_namespaces,
            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 local == "AlternateContent" || local == "sdt" {
            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";

    #[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], &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], &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], &Limits::default())
            .unwrap()
            .unwrap();
        assert!(streamed.has_cross_block_features);
    }
}