f-office-opc 0.3.0

Open Packaging Conventions container: ZIP package and relationships, with input limits.
Documentation
//! Small packages for the tests of the crates that read packages, behind the feature
//! `testing`: the parts of a package with their relationships, zipped, and the namespaces of
//! relationships, written once. A format crate adds the parts of its own format on top.

use std::io::{Cursor, Write as _};

use ::zip::ZipWriter;
use ::zip::result::ZipResult;
use ::zip::write::SimpleFileOptions;

/// The namespace of the relationship IDs in the parts of Office Open XML, which also starts the
/// type of each relationship that ECMA-376 Part 1 defines.
pub const RELATIONSHIPS: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships";

/// The namespace of a relationships part (ECMA-376 Part 2).
pub const PACKAGE_RELATIONSHIPS: &str = crate::RELATIONSHIPS_NS;

/// The parts of a package and the relationships of each part, which [`Builder::zip`] zips with
/// a relationships part for each part that has relationships.
#[derive(Debug, Default)]
pub struct Builder {
    /// The parts by name, in order.
    parts: Vec<(String, Vec<u8>)>,
    /// The relationship elements, each with the name of its source part, or `""` for the
    /// package.
    relationships: Vec<(String, String)>,
}

impl Builder {
    /// Adds the part `name` with the bytes `content`.
    #[must_use]
    pub fn part(mut self, name: &str, content: impl Into<Vec<u8>>) -> Self {
        self.parts.push((name.to_owned(), content.into()));
        self
    }

    /// Adds a relationship of the part `source`, or of the package for `""`, with the ID `id`,
    /// the type `kind` under [`RELATIONSHIPS`] and the target `target`.
    #[must_use]
    pub fn relationship(mut self, source: &str, id: &str, kind: &str, target: &str) -> Self {
        let element =
            format!(r#"<Relationship Id="{id}" Type="{RELATIONSHIPS}/{kind}" Target="{target}"/>"#);
        self.relationships.push((source.to_owned(), element));
        self
    }

    /// Adds a relationship as [`Builder::relationship`] does, whose target `target` lies outside
    /// the package (`TargetMode="External"`), such as the address of a hyperlink.
    #[must_use]
    pub fn external_relationship(
        mut self,
        source: &str,
        id: &str,
        kind: &str,
        target: &str,
    ) -> Self {
        let element = format!(
            r#"<Relationship Id="{id}" Type="{RELATIONSHIPS}/{kind}" Target="{target}" TargetMode="External"/>"#
        );
        self.relationships.push((source.to_owned(), element));
        self
    }

    /// The entries of the package: each part in order, then the relationships part of each
    /// source, in the order of its first relationship.
    #[must_use]
    pub fn entries(self) -> Vec<(String, Vec<u8>)> {
        let mut sources: Vec<(String, String)> = Vec::new();
        for (source, element) in self.relationships {
            match sources.iter_mut().find(|(name, _)| *name == source) {
                Some((_, elements)) => elements.push_str(&element),
                None => sources.push((source, element)),
            }
        }
        let mut entries = self.parts;
        entries.extend(sources.into_iter().map(|(source, elements)| {
            let xml = format!(
                r#"<Relationships xmlns="{PACKAGE_RELATIONSHIPS}">{elements}</Relationships>"#
            );
            (crate::relationships_part(&source), xml.into_bytes())
        }));
        entries
    }

    /// Zips [`Builder::entries`].
    ///
    /// # Errors
    ///
    /// Returns the error of the ZIP writer, as for two entries of one name.
    pub fn zip(self) -> ZipResult<Vec<u8>> {
        zip(self.entries())
    }
}

/// Zips `entries`, each a name and its bytes, in order: for a test that changes the entries of a
/// [`Builder`] first, as one that leaves an entry out.
///
/// # Errors
///
/// Returns the error of the ZIP writer, as for two entries of one name.
pub fn zip(entries: impl IntoIterator<Item = (String, Vec<u8>)>) -> ZipResult<Vec<u8>> {
    let mut out = ZipWriter::new(Cursor::new(Vec::new()));
    for (name, bytes) in entries {
        out.start_file(name, SimpleFileOptions::default())?;
        out.write_all(&bytes)?;
    }
    Ok(out.finish()?.into_inner())
}

#[cfg(test)]
mod tests {
    use super::Builder;
    use crate::{Limits, Package, relationships_part};

    #[test]
    fn names_the_relationships_part_of_a_part_and_of_the_package() {
        assert_eq!(relationships_part(""), "_rels/.rels");
        assert_eq!(
            relationships_part("word/document.xml"),
            "word/_rels/document.xml.rels"
        );
        assert_eq!(relationships_part("a.xml"), "_rels/a.xml.rels");
    }

    #[test]
    fn zips_a_package_that_the_reader_opens_with_its_relationships() {
        let bytes = Builder::default()
            .relationship("", "main", "officeDocument", "word/document.xml")
            .part("word/document.xml", "<w/>")
            .relationship("word/document.xml", "s", "styles", "styles.xml")
            .part("word/styles.xml", "<s/>")
            .relationship("word/document.xml", "h", "header", "h.xml")
            .zip()
            .unwrap();
        let package = Package::open(&bytes, &Limits::default()).unwrap();
        assert_eq!(package.main_document().unwrap(), "word/document.xml");
        let targets: Vec<_> = package
            .relationships("word/document.xml")
            .unwrap()
            .relationships
            .iter()
            .map(|rel| (rel.id.as_str(), rel.target.as_str()))
            .collect();
        assert_eq!(targets, [("s", "word/styles.xml"), ("h", "word/h.xml")]);
    }
}