Brotlic
Brotlic (or BrotlyC) 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.
Requirements
A C compiler is required for building brotli with cargo.
Usage
When dealing with BufRead:
DecompressorReader<R>- Reads a brotli compressed input stream and decompresses it.CompressorReader<R>- Reads a stream and compresses it while reading.
When dealing with Write:
CompressorWriter<W>- Writes brotli compressed data to the underlying writer.DecompressorWriter<W>- Writes brotli decompressed data to the underlying writer.
To simplify this decision, the following table outlines all the differences:
| Input | Output | Wraps | |
|---|---|---|---|
CompressorReader<R> |
Uncompressed | Compressed | BufRead |
DecompressorReader<R> |
Compressed | Uncompressed | BufRead |
CompressorWriter<W> |
Uncompressed | Compressed | Write |
DecompressorWriter<W> |
Compressed | Uncompressed | Write |
To compress a file with brotli:
use File;
use ;
use CompressorWriter;
let mut input = open?; // uncompressed text file
let mut output = create?; // compressed text output file
let mut output_compressed = new;
output_compressed.write_all?;
To decompress that same file:
use File;
use ;
use DecompressorReader;
let mut input = new; // uncompressed text file
let mut input_decompressed = new; // requires BufRead
let mut text = Stringnew;
input_decompressed.read_to_string?;
assert_eq!;
To compress and decompress in memory:
use ;
use ;
let input = vec!;
// create a wrapper around Write that supports on the fly brotli compression.
let mut compressor = new; // write to memory
compressor.write_all;
let encoded_input = compressor.into_inner?.into_inner; // read to vec
// create a wrapper around BufRead that supports on the fly brotli decompression.
let mut decompressed_reader = new;
let mut decoded_input = Vecnew;
decompressed_reader.read_to_end?;
assert_eq!;
Customizing compression quality
Sometimes it can be desirable to trade run-time costs for an even better compression ratio:
use Cursor;
use ;
let encoder = new
.quality
.window_size
.block_size
.build?;
let writer = new;
let compressed_writer = with_encoder;
It is recommended to not use the encoder directly but instead pass it onto the higher level abstractions.
Credits
- brotli library - for the underlying C library
- JetBrains - for their amazing tooling