Skip to main content

eazip/write/
mod.rs

1//! Utilities to write an archive.
2
3use crate::{
4    CompressionMethod, Timestamp,
5    compression::Compressor,
6    io,
7    utils::{Counter, Crc32Writer},
8};
9use alloc::{fmt, vec::Vec};
10
11mod raw;
12
13/// The options used when adding a file to an archive.
14///
15/// Setting the timestamp is not implemented yet.
16#[derive(Debug, Default, Clone)]
17#[non_exhaustive]
18pub struct FileOptions {
19    /// The compression method.
20    pub compression_method: CompressionMethod,
21    /// The compression level.
22    pub level: Option<i32>,
23    /// The modification time of the entry.
24    ///
25    /// Default value is `Timestamp::UNIX_EPOCH`, which means that this field is
26    /// ignored.
27    pub modified_at: Timestamp,
28    /// Unix mode for the entry. The value is masked with `0o7777`, so only the
29    /// first 12 bits are used.
30    pub unix_mode: u32,
31}
32
33impl FileOptions {
34    /// Sets the compression method and level of the options.
35    pub fn compression(mut self, method: CompressionMethod, level: Option<i32>) -> Self {
36        self.compression_method = method;
37        self.level = level;
38        self
39    }
40
41    /// Sets the modification time of the entry.
42    pub fn modified_at(mut self, modified_at: Timestamp) -> Self {
43        self.modified_at = modified_at;
44        self
45    }
46
47    /// Sets the Unix mode of the entry.
48    pub fn unix_mode(mut self, unix_mode: u32) -> Self {
49        self.unix_mode = unix_mode;
50        self
51    }
52}
53
54/// Wraps a writer to create a ZIP archive.
55///
56/// You need to call `self.finish()` when done.
57///
58/// When adding a file to the archive, some checks are made to ensure its name
59/// is valid (it is not absolute, does not contain the '\\' character, etc).
60/// Such validation checks may be added in a semver-compatible version if they
61/// may prevent invalid or dangerous archives.
62///
63/// # Example
64///
65/// ```no_run
66/// use std::io::prelude::*;
67///
68/// let mut archive = eazip::ArchiveWriter::create("example.zip")?;
69/// let options = eazip::write::FileOptions::default();
70///
71/// // Add a file
72/// archive.add_file("hello.txt", b"hello\n".as_slice(), &options)?;
73///
74/// // Add a directory
75/// archive.add_directory("dir/")?;
76///
77/// // Stream a file
78/// let mut writer = archive.stream_file("dir/streaming.txt", &options)?;
79/// writer.write_all(b"some data\n")?;
80/// writer.finish()?;
81///
82/// // Finish writing the archive
83/// archive.finish()?;
84/// # Ok::<(), std::io::Error>(())
85/// ```
86#[derive(Debug, Default)]
87pub struct ArchiveWriter<W: io::Write> {
88    writer: W,
89    raw: raw::RawArchiveWriter,
90}
91
92#[cfg(feature = "std")]
93impl ArchiveWriter<std::fs::File> {
94    /// Creates a new `ArchiveWriter` that writes to the given file.
95    ///
96    /// The file will be created if it does not exist, and will be truncated if
97    /// it does.
98    pub fn create(path: impl AsRef<std::path::Path>) -> io::Result<Self> {
99        std::fs::File::create(path).map(Self::new)
100    }
101
102    /// Creates a new `ArchiveWriter` that writes to the given file; error if
103    /// the file exists.
104    pub fn create_new(path: impl AsRef<std::path::Path>) -> io::Result<Self> {
105        std::fs::File::create_new(path).map(Self::new)
106    }
107}
108
109impl<W: io::Write> ArchiveWriter<W> {
110    /// Creates a new `ArchiveWriter` that writes to the given writer.
111    #[inline]
112    pub fn new(writer: W) -> Self {
113        ArchiveWriter {
114            writer,
115            raw: raw::RawArchiveWriter::default(),
116        }
117    }
118
119    /// Writes a file to the archive.
120    ///
121    /// The entire compressed content of the file must fit in memory.
122    pub fn add_file<R: io::Read>(
123        &mut self,
124        name: &str,
125        mut content: R,
126        options: &FileOptions,
127    ) -> io::Result<()> {
128        let mut w = Crc32Writer::new(Compressor::new(
129            Vec::new(),
130            options.compression_method,
131            options.level,
132        )?);
133        let uncompressed_size = io::copy(&mut content, &mut w)?;
134        let crc32 = w.result();
135        let compressed = w.into_inner().finish()?;
136
137        self.raw.write_file_raw(
138            &mut self.writer,
139            name,
140            &compressed,
141            &raw::Metadata {
142                compression_method: options.compression_method,
143                compressed_size: compressed.len() as _,
144                uncompressed_size,
145                crc32,
146                typ: crate::FileType::File,
147                modified_at: options.modified_at,
148                unix_mode: options.unix_mode,
149            },
150            "",
151        )?;
152
153        Ok(())
154    }
155
156    /// Starts streaming a file to the archive.
157    ///
158    /// This is useful for (but not limited to) very large files that may not
159    /// fit in memory.
160    ///
161    /// This method returns a `FileStreamer` that can be written to.
162    pub fn stream_file(
163        &mut self,
164        name: &str,
165        options: &FileOptions,
166    ) -> io::Result<FileStreamer<'_, W>> {
167        let writer = self.raw.start_stream_raw(&mut self.writer, name, options)?;
168
169        Ok(FileStreamer {
170            writer: Counter::new(Crc32Writer::new(Compressor::new(
171                writer,
172                options.compression_method,
173                options.level,
174            )?)),
175        })
176    }
177
178    /// Adds a directory to the archive.
179    pub fn add_directory(&mut self, name: &str) -> io::Result<()> {
180        self.raw.write_file_raw(
181            &mut self.writer,
182            name,
183            &[],
184            &raw::Metadata {
185                compression_method: CompressionMethod::STORE,
186                compressed_size: 0,
187                uncompressed_size: 0,
188                crc32: 0,
189                typ: crate::FileType::Directory,
190                modified_at: Timestamp::UNIX_EPOCH,
191                unix_mode: 0,
192            },
193            "",
194        )
195    }
196
197    /// Adds a symlink to the archive.
198    ///
199    /// The target of the symlink is not validated yet, which may be used to
200    /// create dangerous archives if used with untrusted input. This will be
201    /// fixed in a future version so this behaviour should not be relied on.
202    pub fn add_symlink(&mut self, name: &str, target: &str) -> io::Result<()> {
203        self.raw.write_file_raw(
204            &mut self.writer,
205            name,
206            target.as_bytes(),
207            &raw::Metadata {
208                compression_method: CompressionMethod::STORE,
209                compressed_size: target.len() as _,
210                uncompressed_size: target.len() as _,
211                crc32: crc32fast::hash(target.as_bytes()),
212                typ: crate::FileType::Symlink,
213                modified_at: Timestamp::UNIX_EPOCH,
214                unix_mode: 0o777,
215            },
216            "",
217        )
218    }
219
220    /// Tries to recover from an error by erasing the last entry.
221    ///
222    /// Note that this requires a seeking writer. Calling this when no error
223    /// needs recovery does nothing.
224    ///
225    /// **Footgun**: this requires the user to properly truncate the writer after
226    /// using this method.
227    #[inline]
228    pub fn recover(&mut self) -> io::Result<()>
229    where
230        W: io::Seek,
231    {
232        self.raw.recover(&mut self.writer)
233    }
234
235    /// Gets a shared reference to the underlying writer.
236    #[inline]
237    pub fn get_ref(&self) -> &W {
238        &self.writer
239    }
240
241    /// Gets a mutable reference to the underlying writer.
242    ///
243    /// It is inadvisable to directly write to the underlying writer.
244    #[inline]
245    pub fn get_mut(&mut self) -> &mut W {
246        &mut self.writer
247    }
248
249    /// Flushes the underlying stream.
250    #[inline]
251    pub fn flush(&mut self) -> io::Result<()> {
252        self.writer.flush()
253    }
254
255    /// Finishes writing the archive and get the writer back.
256    ///
257    /// It is necessary to call this method or the resulting archive will not
258    /// be readable.
259    #[inline]
260    pub fn finish(mut self) -> io::Result<W> {
261        self.raw.finish(&mut self.writer)?;
262        Ok(self.writer)
263    }
264}
265
266/// An adapter to stream a ZIP file.
267///
268/// Writing to this value will write to a file in an archive.
269///
270/// It is necessary to call `finish` when done.
271pub struct FileStreamer<'a, W: io::Write> {
272    writer: Counter<Crc32Writer<Compressor<raw::RawFileStreamer<'a, &'a mut W>>>>,
273}
274
275impl<W: io::Write> io::Write for FileStreamer<'_, W> {
276    #[inline]
277    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
278        self.writer.write(buf)
279    }
280
281    #[inline]
282    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
283        self.writer.write_vectored(bufs)
284    }
285
286    #[inline]
287    fn flush(&mut self) -> io::Result<()> {
288        self.writer.flush()
289    }
290}
291
292impl<W: io::Write> FileStreamer<'_, W> {
293    /// Finishes writing the current file.
294    pub fn finish(self) -> io::Result<()> {
295        self.finish_with_comment("")
296    }
297
298    /// Finishes writing the current file.
299    pub fn finish_with_comment(self, comment: &str) -> io::Result<()> {
300        let uncompressed_size = self.writer.amt;
301        let crc32 = self.writer.inner.result();
302
303        let raw_writer = self.writer.inner.into_inner().finish()?;
304
305        raw_writer.finish(uncompressed_size, crc32, comment)
306    }
307}
308
309impl<'a, W: io::Write + fmt::Debug> fmt::Debug for FileStreamer<'a, W> {
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        f.write_str("FileStreamer { .. }")
312    }
313}