How can I convert a ZipWriter to Bytes in Rust?

I want to create a zip from a certain file, then i convert this zip (A buffer, not a file in the disk) to bytes, then to send it by a post body to an api.

Thats the code (simplifyed) just with the essencial, and from now to the next step, how can i convert it into bytes?

pub fn to_zip() {
    let buf: &mut [u8] = &mut [0u8; 65536];
    let w = std::io::Cursor::new(buf);
    let mut zip = zip::ZipWriter::new(w);

    // * Convert the buffer to bytes

    zip.finish().unwrap();
}

Sorry for a maybe confuse code first time with Rust beeing loving it so far!

The buf you have in your code is for the output, not the input. So, once you have called zip.start_file() on the relevant files and you have called zip.finish(), the buffer should have the zipped content. You can then send it over.

1 Like

The zip.finish() method will return a result containing your original writer, w (a std::io::Cursor<&mut [u8]>). You can use this to find out how many bytes were written, and from there we can access the original buffer and get the compressed bytes.

use std::io::Cursor;
use zip::ZipWriter;

pub fn to_zip() {
    let mut buf = [0u8; 65536];
    let cursor = Cursor::new(&mut buf[..]);
    let mut zip = ZipWriter::new(cursor);

    // TODO: write stuff to the zip writer

    // Finish writing and get the original cursor back
    let cursor = zip.finish().unwrap();

    // Ask the cursor how many bytes were written
    let bytes_written = cursor.position();
    // And get a reference to the original [u8] slice
    let buf = cursor.get_ref();
    // These are the bytes we want
    let compressed_bytes = &buf[..bytes_written as usize];
}

This could be written differently using scoping/helper functions to avoid the .get_ref() awkwardness, but the result would be the same.

3 Likes