f-office 0.2.4

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! The checks of the round trip:
//! whether the bytes of each element's span in each XML part of a package parse back to the same
//! element, with the namespace declarations in scope at its place ([`spans`]), and whether the
//! package writer saves a package with no change as the same bytes and with every part replaced
//! by its own bytes as the same parts ([`save`]), and what one named edit of each operation gives
//! ([`edits`]).

use std::ops::AddAssign;

use f_office_opc::{Limits, Package, PartChange, WriteError, write_package};
use f_office_xml::{Document, Equality, Error as XmlError, NodeId};

use crate::Error;

pub mod edits;

/// The endings of the names of the parts that the check reads as XML, in lower case.
const XML_ENDINGS: [&str; 3] = [".xml", ".rels", ".vml"];

/// What the span check found in a package, or in several ([`AddAssign`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SpanCounts {
    /// The XML parts read: those whose names end in `.xml`, `.rels` or `.vml`, in any case.
    pub parts: usize,
    /// The parts that the reader could not parse, other than those not in UTF-8.
    pub unreadable: usize,
    /// The parts not in UTF-8, as their byte order mark or XML declaration says, whose spans
    /// are not given.
    pub not_utf8: usize,
    /// The elements whose spans were checked.
    pub elements: usize,
    /// The elements whose spans use a prefix that the part itself does not declare: a part may
    /// hold one, with a warning, and a fragment may not ([`f_office_xml::Error::UndeclaredPrefix`]).
    pub undeclared: usize,
    /// The elements whose spans do not parse as a fragment for another reason.
    pub unparsed: usize,
    /// The elements whose spans parse to another element, or to more or fewer nodes than one.
    pub differing: usize,
}

impl SpanCounts {
    /// The elements whose spans do not read back: those with an undeclared prefix, those that
    /// do not parse and those that differ.
    #[must_use]
    pub const fn not_read_back(&self) -> usize {
        self.undeclared + self.unparsed + self.differing
    }
}

impl AddAssign for SpanCounts {
    fn add_assign(&mut self, other: Self) {
        self.parts += other.parts;
        self.unreadable += other.unreadable;
        self.not_utf8 += other.not_utf8;
        self.elements += other.elements;
        self.undeclared += other.undeclared;
        self.unparsed += other.unparsed;
        self.differing += other.differing;
    }
}

/// How the bytes of an element's span read back.
enum ReadBack {
    /// To one element that equals it.
    Same,
    /// Not, because they use a prefix that the part does not declare.
    Undeclared,
    /// Not: they do not parse as a fragment.
    Unparsed,
    /// To another element, or to more or fewer nodes than one.
    Differing,
}

/// Checks the span of every element of every XML part of the package `docx`: its bytes parse,
/// with the namespace declarations in scope at the element's parent, to one element that has
/// the same names, attributes and content. It counts apart the elements that do not read back
/// because the part uses a prefix that it does not declare.
///
/// # Errors
///
/// Returns [`Error::Package`] when the package does not open.
pub fn spans(docx: &[u8]) -> Result<SpanCounts, Error> {
    let limits = Limits::default();
    let package = Package::open(docx, &limits).map_err(Error::Package)?;
    let mut counts = SpanCounts::default();
    for name in package.part_names() {
        let lower = name.to_ascii_lowercase();
        if !XML_ENDINGS.iter().any(|ending| lower.ends_with(ending)) {
            continue;
        }
        let Some(bytes) = package.part(name) else {
            continue;
        };
        counts.parts += 1;
        counts += part_spans(bytes, &limits);
    }
    Ok(counts)
}

/// The span check of one part, with its counts of unreadable parts, parts not in UTF-8,
/// elements and elements that do not read back, by reason.
fn part_spans(bytes: &[u8], limits: &Limits) -> SpanCounts {
    let mut counts = SpanCounts::default();
    let utf16 = bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]);
    let Ok(document) = Document::parse(bytes, &limits.xml) else {
        if utf16 {
            counts.not_utf8 += 1;
        } else {
            counts.unreadable += 1;
        }
        return counts;
    };
    let Ok(root) = document.root() else {
        counts.unreadable += 1;
        return counts;
    };
    if let Err(XmlError::NotUtf8(_)) = document.span(root) {
        counts.not_utf8 += 1;
        return counts;
    }
    let mut open: Vec<(NodeId, Option<NodeId>)> = vec![(root, None)];
    while let Some((id, parent)) = open.pop() {
        open.extend(document.child_elements(id).map(|child| (child, Some(id))));
        counts.elements += 1;
        match read_back(&document, bytes, (id, parent), limits) {
            ReadBack::Same => {}
            ReadBack::Undeclared => counts.undeclared += 1,
            ReadBack::Unparsed => counts.unparsed += 1,
            ReadBack::Differing => counts.differing += 1,
        }
    }
    counts
}

/// How the bytes of the span of the element `id`, whose parent is `parent`, read back.
fn read_back(
    document: &Document,
    bytes: &[u8],
    (id, parent): (NodeId, Option<NodeId>),
    limits: &Limits,
) -> ReadBack {
    let Some(spanned) = document.span(id).ok().and_then(|span| bytes.get(span)) else {
        return ReadBack::Differing;
    };
    let in_scope = parent.map(|parent| document.namespaces_in_scope(parent));
    let fragment = match Document::parse_fragment(
        spanned,
        in_scope.as_deref().unwrap_or_default(),
        &limits.xml,
    ) {
        Ok(fragment) => fragment,
        Err(XmlError::UndeclaredPrefix(prefix))
            if document.undeclared_prefixes().contains(&prefix) =>
        {
            return ReadBack::Undeclared;
        }
        Err(_) => return ReadBack::Unparsed,
    };
    match fragment.nodes() {
        [node] if document.same_tree(id, (fragment.document(), *node), Equality::AsWritten) => {
            ReadBack::Same
        }
        _ => ReadBack::Differing,
    }
}

/// What the package writer gives for a package with no change.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Saved {
    /// The package's own bytes.
    Same,
    /// Other bytes.
    Changed,
    /// No package: the package uses ZIP64, which the writer does not write.
    Zip64,
    /// No package, for another reason.
    NotWritten,
}

/// What the save check found in a package.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SaveCheck {
    /// The package that the writer gives with no change.
    pub saved: Saved,
    /// Whether the package with every part replaced by its own bytes opens with the same parts,
    /// or `None` when the writer does not write it.
    pub rewritten: Option<bool>,
}

/// Saves the package `docx` with the package writer twice: with no change, and with every part
/// replaced by its own bytes, which writes each entry anew.
///
/// # Errors
///
/// Returns [`Error::Package`] when the package does not open.
pub fn save(docx: &[u8]) -> Result<SaveCheck, Error> {
    let limits = Limits::default();
    let package = Package::open(docx, &limits).map_err(Error::Package)?;
    let saved = match write_package(docx, &[], &limits) {
        Ok(bytes) if bytes == docx => Saved::Same,
        Ok(_) => Saved::Changed,
        Err(WriteError::Zip64) => Saved::Zip64,
        Err(_) => Saved::NotWritten,
    };
    let changes: Vec<PartChange<'_>> = package
        .part_names()
        .filter_map(|name| {
            let data = package.part(name)?;
            Some(PartChange::Replace { name, data })
        })
        .collect();
    let rewritten = write_package(docx, &changes, &limits)
        .ok()
        .map(|bytes| same_parts(&package, &bytes, &limits));
    Ok(SaveCheck { saved, rewritten })
}

/// Whether `bytes` open as a package with the parts of `package`, by name and bytes.
fn same_parts(package: &Package, bytes: &[u8], limits: &Limits) -> bool {
    let Ok(other) = Package::open(bytes, limits) else {
        return false;
    };
    package.part_names().eq(other.part_names())
        && package
            .part_names()
            .all(|name| package.part(name) == other.part(name))
}

#[cfg(test)]
mod tests;