async_compression/
brotli.rs

1//! This module contains Brotli-specific types for async-compression.
2
3use brotli::enc::backward_references::{BrotliEncoderMode, BrotliEncoderParams};
4
5/// Brotli compression parameters builder. This is a stable wrapper around Brotli's own encoder
6/// params type, to abstract over different versions of the Brotli library.
7///
8/// See the [Brotli documentation](https://www.brotli.org/encode.html#a9a8) for more information on
9/// these parameters.
10///
11/// # Examples
12///
13/// ```
14/// use async_compression::brotli;
15///
16/// let params = brotli::EncoderParams::default()
17///     .window_size(12)
18///     .text_mode();
19/// ```
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21pub struct EncoderParams {
22    window_size: Option<i32>,
23    block_size: Option<i32>,
24    size_hint: Option<usize>,
25    mode: Option<BrotliEncoderMode>,
26}
27
28impl EncoderParams {
29    /// Sets window size in bytes (as a power of two).
30    ///
31    /// Used as Brotli's `lgwin` parameter.
32    ///
33    /// `window_size` is clamped to `0 <= window_size <= 24`.
34    pub fn window_size(mut self, window_size: i32) -> Self {
35        self.window_size = Some(window_size.clamp(0, 24));
36        self
37    }
38
39    /// Sets input block size in bytes (as a power of two).
40    ///
41    /// Used as Brotli's `lgblock` parameter.
42    ///
43    /// `block_size` is clamped to `16 <= block_size <= 24`.
44    pub fn block_size(mut self, block_size: i32) -> Self {
45        self.block_size = Some(block_size.clamp(16, 24));
46        self
47    }
48
49    /// Sets hint for size of data to be compressed.
50    pub fn size_hint(mut self, size_hint: usize) -> Self {
51        self.size_hint = Some(size_hint);
52        self
53    }
54
55    /// Sets encoder to text mode.
56    ///
57    /// If input data is known to be UTF-8 text, this allows the compressor to make assumptions and
58    /// optimizations.
59    ///
60    /// Used as Brotli's `mode` parameter.
61    pub fn text_mode(mut self) -> Self {
62        self.mode = Some(BrotliEncoderMode::BROTLI_MODE_TEXT);
63        self
64    }
65
66    pub(crate) fn as_brotli(&self) -> BrotliEncoderParams {
67        let mut params = BrotliEncoderParams::default();
68
69        let Self {
70            window_size,
71            block_size,
72            size_hint,
73            mode,
74        } = self;
75
76        if let Some(window_size) = window_size {
77            params.lgwin = *window_size;
78        }
79
80        if let Some(block_size) = block_size {
81            params.lgblock = *block_size;
82        }
83
84        if let Some(size_hint) = size_hint {
85            params.size_hint = *size_hint;
86        }
87
88        if let Some(mode) = mode {
89            params.mode = *mode;
90        }
91
92        params
93    }
94}