Skip to main content

compression_codecs/brotli/
decoder.rs

1use crate::DecodeV2;
2use brotli::{enc::StandardAlloc, BrotliDecompressStream, BrotliResult};
3use compression_core::util::{PartialBuffer, WriteBuffer};
4use std::{fmt, io};
5
6type BrotliState = brotli::BrotliState<StandardAlloc, StandardAlloc, StandardAlloc>;
7
8pub struct BrotliDecoder {
9    // `BrotliState` is very large (over 2kb) which is why we're boxing it.
10    state: Box<BrotliState>,
11    large_window: bool,
12}
13
14impl Default for BrotliDecoder {
15    fn default() -> Self {
16        Self::with_large_window(false)
17    }
18}
19
20impl BrotliDecoder {
21    fn with_large_window(large_window: bool) -> Self {
22        Self {
23            state: Box::new(Self::new_brotli_state(large_window)),
24            large_window,
25        }
26    }
27
28    /// `BrotliState::new` accepts the non-standard large-window format (RFC 9841), whose header
29    /// can declare a window of up to 1 GiB, and the ring buffer is sized from it. A few hundred
30    /// bytes of input could then make the decoder allocate ~1 GiB, regardless of how much output
31    /// the caller reads. So only accept RFC 7932 windows (at most 16 MiB) unless the caller opts
32    /// in, as the `mbrotli` backend does; `BrotliEncoder` never produces large-window streams.
33    fn new_brotli_state(large_window: bool) -> BrotliState {
34        let new = if large_window {
35            BrotliState::new
36        } else {
37            BrotliState::new_strict
38        };
39        new(
40            StandardAlloc::default(),
41            StandardAlloc::default(),
42            StandardAlloc::default(),
43        )
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).
54    ///
55    /// A large-window stream can declare a window of up to 1 GiB, which the decoder allocates
56    /// however few bytes the stream decodes to, so only use this for trusted input. Large windows
57    /// are not valid in the HTTP `br` content coding.
58    pub fn new_with_large_window() -> Self {
59        Self::with_large_window(true)
60    }
61
62    fn decode(
63        &mut self,
64        input: &mut PartialBuffer<&[u8]>,
65        output: &mut WriteBuffer<'_>,
66    ) -> io::Result<BrotliResult> {
67        let in_buf = input.unwritten();
68        let out_buf = output.initialize_unwritten();
69
70        let mut input_len = 0;
71        let mut output_len = 0;
72
73        let status = match BrotliDecompressStream(
74            &mut in_buf.len(),
75            &mut input_len,
76            in_buf,
77            &mut out_buf.len(),
78            &mut output_len,
79            out_buf,
80            &mut 0,
81            &mut self.state,
82        ) {
83            BrotliResult::ResultFailure => return Err(io::Error::other("brotli error")),
84            status => status,
85        };
86
87        input.advance(input_len);
88        output.advance(output_len);
89
90        Ok(status)
91    }
92}
93
94impl DecodeV2 for BrotliDecoder {
95    fn reinit(&mut self) -> io::Result<()> {
96        *self.state = Self::new_brotli_state(self.large_window);
97        Ok(())
98    }
99
100    fn decode(
101        &mut self,
102        input: &mut PartialBuffer<&[u8]>,
103        output: &mut WriteBuffer<'_>,
104    ) -> io::Result<bool> {
105        match self.decode(input, output)? {
106            BrotliResult::ResultSuccess => Ok(true),
107            BrotliResult::NeedsMoreOutput | BrotliResult::NeedsMoreInput => Ok(false),
108            BrotliResult::ResultFailure => unreachable!(),
109        }
110    }
111
112    fn flush(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
113        match self.decode(&mut PartialBuffer::new(&[][..]), output)? {
114            BrotliResult::ResultSuccess | BrotliResult::NeedsMoreInput => Ok(true),
115            BrotliResult::NeedsMoreOutput => Ok(false),
116            BrotliResult::ResultFailure => unreachable!(),
117        }
118    }
119
120    fn finish(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
121        match self.decode(&mut PartialBuffer::new(&[][..]), output)? {
122            BrotliResult::ResultSuccess => Ok(true),
123            BrotliResult::NeedsMoreOutput => Ok(false),
124            BrotliResult::NeedsMoreInput => Err(io::Error::new(
125                io::ErrorKind::UnexpectedEof,
126                "reached unexpected EOF",
127            )),
128            BrotliResult::ResultFailure => unreachable!(),
129        }
130    }
131}
132
133impl fmt::Debug for BrotliDecoder {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.debug_struct("BrotliDecoder")
136            .field("decompress", &"<no debug>")
137            .field("large_window", &self.large_window)
138            .finish()
139    }
140}