Brotli compression

Hello everyone,

I have a bit of a naive question that no doubt will show my experience. I have been exploring the rust-brotli crate (https://crates.io/crates/brotli) with the hopes of improving the compression ratio and speed that I am currently getting using a deflate-based algorithm. Despite the examples and documentation provided by the Brotli maintainers, I can't seem to figure out how I can use this library to compress a simple Vector. I have an uncompressed vector of byte data and I want to generate a compressed vector of bytes. This seems obvious, but I have no experience with this. I was hoping someone on this forum might be have some insight. Thanks in advance.

Cheers,

John

Something like this should work:

use std::io::Write;

pub fn compress(input: &[u8]) -> Vec<u8> {
    let mut writer = brotli::CompressorWriter::new(
        Vec::new(),
        4096,
        11,
        22);
    writer.write_all(input).unwrap();
    writer.into_inner()
}
2 Likes

That is so helpful @mbrubeck thank you for taking the time to reply.

@mbrubeck I realize that this is quite a bit later, but do you happen to know how one would decompress to a Vec? I've tried adapting your code for compressing, using brotli::DecompressWriter::new() instead. However, the 'writer.into_inner()' seems to return a Result<W, W> rather than a single writer. I'm very confused by the usage of this brotli library and I'm afraid that I can't make heads or tails of the documentation. I would appreciate any insight you may have.

It returns an error if the decompression failed in some manner. It still gives you the Vec<u8> back in that case as you might want your writer back, even if decompression failed or was incomplete.

@alice Ah, that makes a lot of sense. I think I get it now.