docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Rendered document output.

use std::io::Write;
use std::path::Path;

/// A rendered DOCX document.
///
/// Wraps the generated ZIP bytes in memory, providing methods to
/// write to a file or extract the raw bytes.
///
/// # Examples
///
/// ```no_run
/// # use docx_templating::{Template, Context};
/// # use serde_json::json;
/// # fn example() -> docx_templating::Result<()> {
/// let template = Template::from_path("template.docx")?;
/// let rendered = template.render(json!({"name": "Ada"}))?;
///
/// // Write to file
/// rendered.write_to_file("output.docx")?;
/// # Ok(())
/// # }
///
/// // Or get raw bytes
/// # fn example2() -> docx_templating::Result<()> {
/// # let template = Template::from_path("template.docx")?;
/// # let rendered = template.render(json!({"name": "Ada"}))?;
/// let bytes = rendered.as_bytes();
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct RenderedDocument {
    bytes: Vec<u8>,
}

impl RenderedDocument {
    /// Create a rendered document from raw DOCX bytes.
    pub(crate) fn new(bytes: Vec<u8>) -> Self {
        Self { bytes }
    }

    /// Write the document to a file.
    ///
    /// # Errors
    ///
    /// Returns error if the file cannot be written.
    pub fn write_to_file(self, path: impl AsRef<Path>) -> crate::Result<()> {
        std::fs::write(path, self.bytes)?;
        Ok(())
    }

    /// Write the rendered DOCX bytes to any `Write` sink.
    ///
    /// Consumes the `RenderedDocument`.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the sink fails.
    pub fn write_to_writer<W: Write>(self, mut writer: W) -> crate::Result<()> {
        writer.write_all(&self.bytes)?;
        Ok(())
    }

    /// Get a reference to the raw DOCX bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Consume the document and return the raw DOCX bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }
}

impl AsRef<[u8]> for RenderedDocument {
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

impl From<RenderedDocument> for Vec<u8> {
    fn from(document: RenderedDocument) -> Self {
        document.bytes
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;

    #[test]
    fn new_stores_bytes() {
        let bytes = vec![1, 2, 3];
        let doc = RenderedDocument::new(bytes.clone());
        assert_eq!(doc.as_bytes(), &bytes);
    }

    #[test]
    fn into_bytes_returns_ownership() {
        let bytes = vec![1, 2, 3];
        let doc = RenderedDocument::new(bytes.clone());
        assert_eq!(doc.into_bytes(), bytes);
    }

    #[test]
    fn as_ref_returns_the_bytes() {
        let doc = RenderedDocument::new(vec![1, 2, 3]);
        let bytes: &[u8] = doc.as_ref();
        assert_eq!(bytes, &[1, 2, 3]);
    }

    #[test]
    fn a_document_converts_into_a_byte_vector() {
        let doc = RenderedDocument::new(vec![1, 2, 3]);
        let bytes: Vec<u8> = doc.into();
        assert_eq!(bytes, vec![1, 2, 3]);
    }
}