Skip to main content

docx_templating/package/
source.rs

1//! `PackageSource` trait — abstract read access to a DOCX/OPC package.
2
3use crate::Result;
4
5/// Read-only access to a DOCX package (ZIP/OPC archive).
6///
7/// Implemented by [`ZipPackageSource`] for file/stream-backed packages and by
8/// [`InMemoryPackageSource`] for in-memory packages used in tests.
9///
10/// Higher-level layers depend on this trait rather than any concrete ZIP type,
11/// which keeps the templating engine independent of storage format.
12///
13/// # Contract
14///
15/// - `part_names` returns only **safe** part names (no path traversal).
16/// - `read_part` returns `None` for unknown parts, never an error for "not found".
17/// - Part names use forward slashes as separators and do NOT start with `/`.
18///
19/// [`ZipPackageSource`]: crate::package::ZipPackageSource
20/// [`InMemoryPackageSource`]: crate::package::InMemoryPackageSource
21pub trait PackageSource {
22    /// Return the names of all parts in this package.
23    ///
24    /// Implementations must filter out unsafe entry names before returning.
25    fn part_names(&self) -> Result<Vec<String>>;
26
27    /// Return `true` if the named part exists in this package.
28    fn contains_part(&self, name: &str) -> Result<bool>;
29
30    /// Read the raw bytes of a part, or `None` if the part does not exist.
31    fn read_part(&self, name: &str) -> Result<Option<Vec<u8>>>;
32
33    /// Return the raw bytes of the underlying archive, if available.
34    ///
35    /// Returning `Some` allows [`ZipPackageWriter`] to copy parts verbatim
36    /// without decompressing and recompressing them. The default returns
37    /// `None`, which causes a safe fallback to decompress + recompress.
38    ///
39    /// [`ZipPackageWriter`]: crate::package::ZipPackageWriter
40    fn raw_archive_bytes(&self) -> Option<&[u8]> {
41        None
42    }
43}