Skip to main content

compression_codecs/mbrotli/
decoder.rs

1use crate::DecodeV2;
2use compression_core::util::{PartialBuffer, WriteBuffer};
3use mbrotli::{
4    DecodeOperation, DecodeStreamConfig, DecoderConfig, DecoderSessionOwned, DecoderStatus,
5    Decompressor, WindowLimit,
6};
7use std::io;
8
9/// Only accept RFC 7932 windows by default, as the `brotli` backend does (via
10/// `BrotliState::new_strict`). Large windows (RFC 9841) are not valid in the `br` content coding.
11const DECODER_CONFIG: DecoderConfig = DecoderConfig::new().with_window_limit(
12    match WindowLimit::standard(mbrotli::Window::MAX_STANDARD_BITS) {
13        Ok(limit) => limit,
14        Err(_) => panic!("the standard window limit is valid"),
15    },
16);
17
18/// With large windows enabled, accept up to 2^30 bytes, the most the `brotli` backend accepts.
19const LARGE_WINDOW_DECODER_CONFIG: DecoderConfig =
20    DecoderConfig::new().with_window_limit(match WindowLimit::large(30) {
21        Ok(limit) => limit,
22        Err(_) => panic!("the large window limit is valid"),
23    });
24
25#[derive(Debug)]
26pub struct MbrotliDecoder {
27    session: DecoderSessionOwned,
28}
29
30impl Default for MbrotliDecoder {
31    fn default() -> Self {
32        Self::with_config(DECODER_CONFIG)
33    }
34}
35
36impl MbrotliDecoder {
37    fn with_config(config: DecoderConfig) -> Self {
38        let decompressor = Decompressor::new(config).unwrap();
39        // A fresh decompressor without an exact output size has no way to refuse a session.
40        let session = decompressor
41            .into_session(DecodeStreamConfig::default())
42            .unwrap();
43        Self { session }
44    }
45
46    /// Creates a decoder that only accepts standard (RFC 7932) brotli streams, whose window is
47    /// at most 16 MiB.
48    pub fn new() -> Self {
49        Self::default()
50    }
51
52    /// Creates a decoder that also accepts the non-standard large-window brotli format
53    /// (RFC 9841), with windows of up to 1 GiB.
54    ///
55    /// A large-window stream chooses its own window, so only use this for trusted input. Large
56    /// windows are not valid in the HTTP `br` content coding.
57    pub fn new_with_large_window() -> Self {
58        Self::with_config(LARGE_WINDOW_DECODER_CONFIG)
59    }
60}
61
62/// Feeds `input` to the session, writing straight into the uninitialized tail of `output`.
63///
64/// Returns how much input was consumed and what the session needs next.
65fn process(
66    session: &mut DecoderSessionOwned,
67    input: &[u8],
68    output: &mut WriteBuffer<'_>,
69    operation: DecodeOperation,
70) -> (usize, io::Result<DecoderStatus>) {
71    // SAFETY: `process_uninit` never de-initializes bytes of `output`.
72    let result = session.process_uninit(input, unsafe { output.unwritten_mut() }, operation);
73    // `process_uninit` initializes exactly `produced` leading bytes of `output`, both when it
74    // succeeds and when it fails.
75    match result {
76        Ok(progress) => {
77            // SAFETY: see above.
78            unsafe { output.assume_init_and_advance(progress.produced) };
79            (progress.consumed, Ok(progress.status))
80        }
81        Err(failure) => {
82            // SAFETY: see above.
83            unsafe { output.assume_init_and_advance(failure.produced) };
84            (failure.consumed, Err(failure.into_error().into()))
85        }
86    }
87}
88
89impl DecodeV2 for MbrotliDecoder {
90    fn reinit(&mut self) -> io::Result<()> {
91        self.session.reinit(DecodeStreamConfig::default())?;
92        Ok(())
93    }
94
95    fn decode(
96        &mut self,
97        input: &mut PartialBuffer<&[u8]>,
98        output: &mut WriteBuffer<'_>,
99    ) -> io::Result<bool> {
100        let (consumed, status) = process(
101            &mut self.session,
102            input.unwritten(),
103            output,
104            DecodeOperation::Process,
105        );
106        input.advance(consumed);
107
108        match status? {
109            DecoderStatus::Finished => Ok(true),
110            DecoderStatus::NeedsInput | DecoderStatus::NeedsOutput => Ok(false),
111        }
112    }
113
114    fn flush(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
115        // Empty input with `Process` delivers pending output without declaring EOF.
116        let (_, status) = process(&mut self.session, &[], output, DecodeOperation::Process);
117
118        match status? {
119            DecoderStatus::Finished | DecoderStatus::NeedsInput => Ok(true),
120            DecoderStatus::NeedsOutput => Ok(false),
121        }
122    }
123
124    fn finish(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
125        // Declaring EOF on a member that is still open fails with `UnexpectedEof`.
126        let (_, status) = process(&mut self.session, &[], output, DecodeOperation::Finish);
127
128        match status? {
129            DecoderStatus::Finished => Ok(true),
130            DecoderStatus::NeedsInput | DecoderStatus::NeedsOutput => Ok(false),
131        }
132    }
133}