Crate brotlic

source ·
Expand description


Brotlic (or BrotliC) is a thin wrapper around brotli. It provides Rust bindings to all compression and decompression APIs. On the fly compression and decompression is supported for both BufRead and Write via [CompressorReader<R>, CompressorWriter<W>, DecompressorReader<R> and DecompressorWriter<W>. For low-level instances, see BrotliEncoder and BrotliDecoder. These can be configured via BrotliEncoderOptions and BrotliDecoderOptions respectively.

§High level abstractions

When dealing with BufRead:

When dealing with Write:

To simplify this decision, the following table outlines all the differences:


To compress a file with brotli:

use std::fs::File;
use std::io::{self, Write};

use brotlic::CompressorWriter;

let mut input = File::open("test.txt")?; // uncompressed text file
let mut output = File::create("test.brotli")?; // compressed text output file
let mut output_compressed = CompressorWriter::new(output);


To decompress that same file:

use std::fs::File;
use std::io::{self, BufReader, Read};

use brotlic::DecompressorReader;

let mut input = BufReader::new(File::open("test.brotli")?); // uncompressed text file
let mut input_decompressed = DecompressorReader::new(input); // requires BufRead

let mut text = String::new();
input_decompressed.read_to_string(&mut text)?;

assert_eq!(text, "test");

To compress and decompress in memory:

use std::io::{self, Read, Write};

use brotlic::{CompressorWriter, DecompressorReader};

let input = vec![0; 1024];

// create a wrapper around Write that supports on the fly brotli compression.
let mut compressor = CompressorWriter::new(Vec::new()); // Vec implements Write
let compressed_input = compressor.into_inner()?; // read to vec

// create a wrapper around BufRead that supports on the fly brotli decompression.
let mut decompressor = DecompressorReader::new(compressed_input.as_slice()); // slice is BufRead
let mut decompressed_input = Vec::new();

decompressor.read_to_end(&mut decompressed_input)?;

assert_eq!(input, decompressed_input);

§Customizing compression quality

Sometimes it can be desirable to trade run-time costs for an even better compression ratio:

use brotlic::{BlockSize, BrotliEncoderOptions, CompressorWriter, Quality, WindowSize};

let encoder = BrotliEncoderOptions::new()

let compressed_writer = CompressorWriter::with_encoder(encoder, Vec::new());

It is recommended to not use the encoder directly but instead pass it onto the higher level abstractions like CompressorWriter<W> or DecompressorReader<R>.



  • Module that contains the brotli decoder instances
  • Module that contains the brotli encoder instances




  • Read all bytes from input and compress them into output, returning how many bytes were written.
  • Returns an upper bound for compression.
  • Returns peak memory usage for a given quality and window size
  • Read all bytes from input and decompress them into output, returning how many bytes were written.