Skip to main content

docx_templating/package/
memory_source.rs

1//! In-memory `PackageSource` implementation for tests and embedded scenarios.
2
3use std::collections::HashMap;
4
5use crate::Result;
6use crate::package::PackageSource;
7
8/// A DOCX package stored entirely in memory.
9///
10/// Useful for:
11/// - Unit and integration tests that don't touch the file system
12/// - Constructing minimal DOCX packages programmatically
13/// - Verifying that higher-level code is decoupled from ZIP storage
14///
15/// # Example
16///
17/// ```rust
18/// use docx_templating::package::{InMemoryPackageSource, PackageSource};
19///
20/// let mut source = InMemoryPackageSource::new();
21/// source.add_part("word/document.xml", b"<root/>".to_vec());
22///
23/// assert!(source.contains_part("word/document.xml").unwrap());
24/// assert_eq!(
25///     source.read_part("word/document.xml").unwrap().unwrap(),
26///     b"<root/>"
27/// );
28/// ```
29#[derive(Debug, Default)]
30pub struct InMemoryPackageSource {
31    parts: HashMap<String, Vec<u8>>,
32}
33
34impl InMemoryPackageSource {
35    /// Create an empty in-memory package.
36    pub fn new() -> Self {
37        Self::default()
38    }
39
40    /// Add or replace a part with the given raw bytes.
41    ///
42    /// `name` should use forward slashes and must not start with `/`.
43    pub fn add_part(&mut self, name: impl Into<String>, data: Vec<u8>) {
44        self.parts.insert(name.into(), data);
45    }
46
47    /// Remove a part, returning its data if it existed.
48    pub fn remove_part(&mut self, name: &str) -> Option<Vec<u8>> {
49        self.parts.remove(name)
50    }
51
52    /// Return the number of parts currently in this package.
53    pub fn len(&self) -> usize {
54        self.parts.len()
55    }
56
57    /// Return `true` if this package contains no parts.
58    pub fn is_empty(&self) -> bool {
59        self.parts.is_empty()
60    }
61}
62
63impl PackageSource for InMemoryPackageSource {
64    fn part_names(&self) -> Result<Vec<String>> {
65        let mut names: Vec<String> = self.parts.keys().cloned().collect();
66        names.sort(); // deterministic ordering for tests
67        Ok(names)
68    }
69
70    fn contains_part(&self, name: &str) -> Result<bool> {
71        Ok(self.parts.contains_key(name))
72    }
73
74    fn read_part(&self, name: &str) -> Result<Option<Vec<u8>>> {
75        Ok(self.parts.get(name).cloned())
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
82
83    use super::*;
84
85    fn minimal_source() -> InMemoryPackageSource {
86        let mut s = InMemoryPackageSource::new();
87        s.add_part("[Content_Types].xml", b"<ct/>".to_vec());
88        s.add_part("_rels/.rels", b"<rels/>".to_vec());
89        s.add_part("word/document.xml", b"<doc/>".to_vec());
90        s
91    }
92
93    #[test]
94    fn new_is_empty() {
95        let s = InMemoryPackageSource::new();
96        assert!(s.is_empty());
97        assert_eq!(s.len(), 0);
98        assert_eq!(s.part_names().unwrap(), Vec::<String>::new());
99    }
100
101    #[test]
102    fn add_and_list_parts() {
103        let s = minimal_source();
104        let names = s.part_names().unwrap();
105        assert_eq!(
106            names,
107            vec!["[Content_Types].xml", "_rels/.rels", "word/document.xml",]
108        );
109    }
110
111    #[test]
112    fn contains_part_true_for_known() {
113        let s = minimal_source();
114        assert!(s.contains_part("word/document.xml").unwrap());
115        assert!(s.contains_part("[Content_Types].xml").unwrap());
116    }
117
118    #[test]
119    fn contains_part_false_for_unknown() {
120        let s = minimal_source();
121        assert!(!s.contains_part("word/header1.xml").unwrap());
122        assert!(!s.contains_part("").unwrap());
123    }
124
125    #[test]
126    fn read_part_returns_bytes() {
127        let s = minimal_source();
128        assert_eq!(
129            s.read_part("word/document.xml").unwrap().unwrap(),
130            b"<doc/>"
131        );
132    }
133
134    #[test]
135    fn read_part_returns_none_for_unknown() {
136        let s = minimal_source();
137        assert!(s.read_part("word/missing.xml").unwrap().is_none());
138    }
139
140    #[test]
141    fn add_part_overwrites_existing() {
142        let mut s = InMemoryPackageSource::new();
143        s.add_part("word/document.xml", b"first".to_vec());
144        s.add_part("word/document.xml", b"second".to_vec());
145        assert_eq!(
146            s.read_part("word/document.xml").unwrap().unwrap(),
147            b"second"
148        );
149        assert_eq!(s.len(), 1);
150    }
151
152    #[test]
153    fn remove_part_returns_data() {
154        let mut s = minimal_source();
155        let data = s.remove_part("word/document.xml");
156        assert_eq!(data.unwrap(), b"<doc/>");
157        assert!(!s.contains_part("word/document.xml").unwrap());
158    }
159
160    #[test]
161    fn part_names_are_sorted() {
162        let mut s = InMemoryPackageSource::new();
163        s.add_part("word/document.xml", vec![]);
164        s.add_part("[Content_Types].xml", vec![]);
165        s.add_part("_rels/.rels", vec![]);
166        let names = s.part_names().unwrap();
167        let mut expected = names.clone();
168        expected.sort();
169        assert_eq!(names, expected);
170    }
171}