Struct zip::write::ZipWriter

source ·
pub struct ZipWriter<W: Write + Seek> { /* private fields */ }
Expand description

ZIP archive generator

Handles the bookkeeping involved in building an archive, and provides an API to edit its contents.

use std::io::Write;
use zip::write::SimpleFileOptions;

// We use a buffer here, though you'd normally use a `File`
let mut buf = [0; 65536];
let mut zip = ZipWriter::new(std::io::Cursor::new(&mut buf[..]));

let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
zip.start_file("hello_world.txt", options)?;
zip.write(b"Hello, World!")?;

// Apply the changes you've made.
// Dropping the `ZipWriter` will have the same effect, but may silently fail
zip.finish()?;

Implementations§

source§

impl<A: Read + Write + Seek> ZipWriter<A>

source

pub fn new_append(readwriter: A) -> ZipResult<ZipWriter<A>>

Initializes the archive from an existing ZIP archive, making it ready for append.

source

pub fn set_flush_on_finish_file(&mut self, flush_on_finish_file: bool)

flush_on_finish_file is designed to support a streaming inner that may unload flushed bytes. It flushes a file’s header and body once it starts writing another file. A ZipWriter will not try to seek back into where a previous file was written unless either ZipWriter::abort_file is called while ZipWriter::is_writing_file returns false, or ZipWriter::deep_copy_file is called. In the latter case, it will only need to read previously-written files and not overwrite them.

Note: when using an inner that cannot overwrite flushed bytes, do not wrap it in a std::io::BufWriter, because that has a Seek::seek method that implicitly calls BufWriter::flush, and ZipWriter needs to seek backward to update each file’s header with the size and checksum after writing the body.

This setting is false by default.

source§

impl<A: Read + Write + Seek> ZipWriter<A>

source

pub fn deep_copy_file( &mut self, src_name: &str, dest_name: &str ) -> ZipResult<()>

Adds another copy of a file already in this archive. This will produce a larger but more widely-compatible archive compared to Self::shallow_copy_file. Does not copy alignment.

source

pub fn deep_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>( &mut self, src_path: T, dest_path: U ) -> ZipResult<()>

Like deep_copy_file, but uses Path arguments.

This function ensures that the ‘/’ path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file’s root.

source

pub fn finish_into_readable(self) -> ZipResult<ZipArchive<A>>

Write the zip file into the backing stream, then produce a readable archive of that data.

This method avoids parsing the central directory records at the end of the stream for a slight performance improvement over running ZipArchive::new() on the output of Self::finish().

 use std::io::{Cursor, prelude::*};
 use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};

 let buf = Cursor::new(Vec::new());
 let mut zip = ZipWriter::new(buf);
 let options = SimpleFileOptions::default();
 zip.start_file("a.txt", options)?;
 zip.write_all(b"hello\n")?;

 let mut zip = zip.finish_into_readable()?;
 let mut s: String = String::new();
 zip.by_name("a.txt")?.read_to_string(&mut s)?;
 assert_eq!(s, "hello\n");
source§

impl<W: Write + Seek> ZipWriter<W>

source

pub fn new(inner: W) -> ZipWriter<W>

Initializes the archive.

Before writing to this object, the ZipWriter::start_file function should be called. After a successful write, the file remains open for writing. After a failed write, call ZipWriter::is_writing_file to determine if the file remains open.

source

pub const fn is_writing_file(&self) -> bool

Returns true if a file is currently open for writing.

source

pub fn set_comment<S>(&mut self, comment: S)
where S: Into<String>,

Set ZIP archive comment.

source

pub fn set_raw_comment(&mut self, comment: Vec<u8>)

Set ZIP archive comment.

This sets the raw bytes of the comment. The comment is typically expected to be encoded in UTF-8

source

pub fn get_comment(&mut self) -> Result<&str, Utf8Error>

Get ZIP archive comment.

source

pub const fn get_raw_comment(&self) -> &Vec<u8>

Get ZIP archive comment.

This returns the raw bytes of the comment. The comment is typically expected to be encoded in UTF-8

source

pub fn abort_file(&mut self) -> ZipResult<()>

Removes the file currently being written from the archive if there is one, or else removes the file most recently written.

source

pub fn start_file<S, T: FileOptionExtension>( &mut self, name: S, options: FileOptions<T> ) -> ZipResult<()>
where S: Into<Box<str>>,

Create a file in the archive and start writing its’ contents. The file must not have the same name as a file already in the archive.

The data should be written using the Write implementation on this ZipWriter

source

pub fn merge_archive<R>(&mut self, source: ZipArchive<R>) -> ZipResult<()>
where R: Read + Seek,

Copy over the entire contents of another archive verbatim.

This method extracts file metadata from the source archive, then simply performs a single big io::copy() to transfer all the actual file contents without any decompression or decryption. This is more performant than the equivalent operation of calling Self::raw_copy_file() for each entry from the source archive in sequence.

 use std::io::{Cursor, prelude::*};
 use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};

 let buf = Cursor::new(Vec::new());
 let mut zip = ZipWriter::new(buf);
 zip.start_file("a.txt", SimpleFileOptions::default())?;
 zip.write_all(b"hello\n")?;
 let src = ZipArchive::new(zip.finish()?)?;

 let buf = Cursor::new(Vec::new());
 let mut zip = ZipWriter::new(buf);
 zip.start_file("b.txt", SimpleFileOptions::default())?;
 zip.write_all(b"hey\n")?;
 let src2 = ZipArchive::new(zip.finish()?)?;

 let buf = Cursor::new(Vec::new());
 let mut zip = ZipWriter::new(buf);
 zip.merge_archive(src)?;
 zip.merge_archive(src2)?;
 let mut result = ZipArchive::new(zip.finish()?)?;

 let mut s: String = String::new();
 result.by_name("a.txt")?.read_to_string(&mut s)?;
 assert_eq!(s, "hello\n");
 s.clear();
 result.by_name("b.txt")?.read_to_string(&mut s)?;
 assert_eq!(s, "hey\n");
source

pub fn start_file_from_path<E: FileOptionExtension, P: AsRef<Path>>( &mut self, path: P, options: FileOptions<E> ) -> ZipResult<()>

Starts a file, taking a Path as argument.

This function ensures that the ‘/’ path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file’s root.

source

pub fn raw_copy_file_rename<S>( &mut self, file: ZipFile<'_>, name: S ) -> ZipResult<()>
where S: Into<Box<str>>,

Add a new file using the already compressed data from a ZIP file being read and renames it, this allows faster copies of the ZipFile since there is no need to decompress and compress it again. Any ZipFile metadata is copied and not checked, for example the file CRC.

use std::fs::File;
use std::io::{Read, Seek, Write};
use zip::{ZipArchive, ZipWriter};

fn copy_rename<R, W>(
    src: &mut ZipArchive<R>,
    dst: &mut ZipWriter<W>,
) -> zip::result::ZipResult<()>
where
    R: Read + Seek,
    W: Write + Seek,
{
    // Retrieve file entry by name
    let file = src.by_name("src_file.txt")?;

    // Copy and rename the previously obtained file entry to the destination zip archive
    dst.raw_copy_file_rename(file, "new_name.txt")?;

    Ok(())
}
source

pub fn raw_copy_file_to_path<P: AsRef<Path>>( &mut self, file: ZipFile<'_>, path: P ) -> ZipResult<()>

Like raw_copy_file_to_path, but uses Path arguments.

This function ensures that the ‘/’ path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file’s root.

source

pub fn raw_copy_file(&mut self, file: ZipFile<'_>) -> ZipResult<()>

Add a new file using the already compressed data from a ZIP file being read, this allows faster copies of the ZipFile since there is no need to decompress and compress it again. Any ZipFile metadata is copied and not checked, for example the file CRC.

use std::fs::File;
use std::io::{Read, Seek, Write};
use zip::{ZipArchive, ZipWriter};

fn copy<R, W>(src: &mut ZipArchive<R>, dst: &mut ZipWriter<W>) -> zip::result::ZipResult<()>
where
    R: Read + Seek,
    W: Write + Seek,
{
    // Retrieve file entry by name
    let file = src.by_name("src_file.txt")?;

    // Copy the previously obtained file entry to the destination zip archive
    dst.raw_copy_file(file)?;

    Ok(())
}
source

pub fn add_directory<S, T: FileOptionExtension>( &mut self, name: S, options: FileOptions<T> ) -> ZipResult<()>
where S: Into<String>,

Add a directory entry.

As directories have no content, you must not call ZipWriter::write before adding a new file.

source

pub fn add_directory_from_path<T: FileOptionExtension, P: AsRef<Path>>( &mut self, path: P, options: FileOptions<T> ) -> ZipResult<()>

Add a directory entry, taking a Path as argument.

This function ensures that the ‘/’ path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file’s root.

source

pub fn finish(&mut self) -> ZipResult<W>

Finish the last file and write all other zip-structures

This will return the writer, but one should normally not append any data to the end of the file. Note that the zipfile will also be finished on drop.

Add a symlink entry.

The zip archive will contain an entry for path name which is a symlink to target.

No validation or normalization of the paths is performed. For best results, callers should normalize \ to / and ensure symlinks are relative to other paths within the zip archive.

WARNING: not all zip implementations preserve symlinks on extract. Some zip implementations may materialize a symlink as a regular file, possibly with the content incorrectly set to the symlink target. For maximum portability, consider storing a regular file instead.

Add a symlink entry, taking Paths to the location and target as arguments.

This function ensures that the ‘/’ path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file’s root.

source

pub fn shallow_copy_file( &mut self, src_name: &str, dest_name: &str ) -> ZipResult<()>

Adds another entry to the central directory referring to the same content as an existing entry. The file’s local-file header will still refer to it by its original name, so unzipping the file will technically be unspecified behavior. ZipArchive ignores the filename in the local-file header and treat the central directory as authoritative. However, some other software (e.g. Minecraft) will refuse to extract a file copied this way.

source

pub fn shallow_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>( &mut self, src_path: T, dest_path: U ) -> ZipResult<()>

Like shallow_copy_file, but uses Path arguments.

This function ensures that the ‘/’ path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file’s root.

Trait Implementations§

source§

impl<W: Write + Seek> Drop for ZipWriter<W>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<W: Write + Seek> Write for ZipWriter<W>

source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Write a buffer into this writer, returning how many bytes were written. Read more
source§

fn flush(&mut self) -> Result<()>

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

§

impl<W> Freeze for ZipWriter<W>
where W: Freeze,

§

impl<W> RefUnwindSafe for ZipWriter<W>
where W: RefUnwindSafe,

§

impl<W> Send for ZipWriter<W>
where W: Send,

§

impl<W> Sync for ZipWriter<W>
where W: Sync,

§

impl<W> Unpin for ZipWriter<W>
where W: Unpin,

§

impl<W> UnwindSafe for ZipWriter<W>
where W: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<W> LittleEndianWriteExt for W
where W: Write,

source§

fn write_u16_le(&mut self, input: u16) -> Result<()>

source§

fn write_u32_le(&mut self, input: u32) -> Result<()>

source§

fn write_u64_le(&mut self, input: u64) -> Result<()>

source§

fn write_u128_le(&mut self, input: u128) -> Result<()>

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<W> WriteBytesExt for W
where W: Write + ?Sized,

source§

fn write_u8(&mut self, n: u8) -> Result<(), Error>

Writes an unsigned 8 bit integer to the underlying writer. Read more
source§

fn write_i8(&mut self, n: i8) -> Result<(), Error>

Writes a signed 8 bit integer to the underlying writer. Read more
source§

fn write_u16<T>(&mut self, n: u16) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned 16 bit integer to the underlying writer. Read more
source§

fn write_i16<T>(&mut self, n: i16) -> Result<(), Error>
where T: ByteOrder,

Writes a signed 16 bit integer to the underlying writer. Read more
source§

fn write_u24<T>(&mut self, n: u32) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned 24 bit integer to the underlying writer. Read more
source§

fn write_i24<T>(&mut self, n: i32) -> Result<(), Error>
where T: ByteOrder,

Writes a signed 24 bit integer to the underlying writer. Read more
source§

fn write_u32<T>(&mut self, n: u32) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned 32 bit integer to the underlying writer. Read more
source§

fn write_i32<T>(&mut self, n: i32) -> Result<(), Error>
where T: ByteOrder,

Writes a signed 32 bit integer to the underlying writer. Read more
source§

fn write_u48<T>(&mut self, n: u64) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned 48 bit integer to the underlying writer. Read more
source§

fn write_i48<T>(&mut self, n: i64) -> Result<(), Error>
where T: ByteOrder,

Writes a signed 48 bit integer to the underlying writer. Read more
source§

fn write_u64<T>(&mut self, n: u64) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned 64 bit integer to the underlying writer. Read more
source§

fn write_i64<T>(&mut self, n: i64) -> Result<(), Error>
where T: ByteOrder,

Writes a signed 64 bit integer to the underlying writer. Read more
source§

fn write_u128<T>(&mut self, n: u128) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned 128 bit integer to the underlying writer.
source§

fn write_i128<T>(&mut self, n: i128) -> Result<(), Error>
where T: ByteOrder,

Writes a signed 128 bit integer to the underlying writer.
source§

fn write_uint<T>(&mut self, n: u64, nbytes: usize) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned n-bytes integer to the underlying writer. Read more
source§

fn write_int<T>(&mut self, n: i64, nbytes: usize) -> Result<(), Error>
where T: ByteOrder,

Writes a signed n-bytes integer to the underlying writer. Read more
source§

fn write_uint128<T>(&mut self, n: u128, nbytes: usize) -> Result<(), Error>
where T: ByteOrder,

Writes an unsigned n-bytes integer to the underlying writer. Read more
source§

fn write_int128<T>(&mut self, n: i128, nbytes: usize) -> Result<(), Error>
where T: ByteOrder,

Writes a signed n-bytes integer to the underlying writer. Read more
source§

fn write_f32<T>(&mut self, n: f32) -> Result<(), Error>
where T: ByteOrder,

Writes a IEEE754 single-precision (4 bytes) floating point number to the underlying writer. Read more
source§

fn write_f64<T>(&mut self, n: f64) -> Result<(), Error>
where T: ByteOrder,

Writes a IEEE754 double-precision (8 bytes) floating point number to the underlying writer. Read more