Skip to main content

brotli/enc/
writer.rs

1#[cfg(feature = "std")]
2use alloc::Allocator;
3use alloc::SliceWrapperMut;
4#[cfg(feature = "std")]
5use std::io;
6#[cfg(feature = "std")]
7use std::io::{Error, ErrorKind, Write};
8
9#[cfg(feature = "std")]
10pub use alloc_stdlib::StandardAlloc;
11use brotli_decompressor::CustomWrite;
12#[cfg(feature = "std")]
13pub use brotli_decompressor::{IntoIoWriter, IoWriterWrapper};
14
15#[cfg(feature = "std")]
16use super::backward_references::BrotliEncoderParams;
17use super::combined_alloc::BrotliAlloc;
18use super::encode::{
19    BrotliEncoderDestroyInstance, BrotliEncoderOperation, BrotliEncoderParameter,
20    BrotliEncoderStateStruct,
21};
22use super::interface;
23#[cfg(feature = "std")]
24use crate::enc::combined_alloc::allocate;
25
26#[cfg(feature = "std")]
27pub struct CompressorWriterCustomAlloc<
28    W: Write,
29    BufferType: SliceWrapperMut<u8>,
30    Alloc: BrotliAlloc,
31>(CompressorWriterCustomIo<io::Error, IntoIoWriter<W>, BufferType, Alloc>);
32
33#[cfg(feature = "std")]
34impl<W: Write, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc>
35    CompressorWriterCustomAlloc<W, BufferType, Alloc>
36{
37    pub fn new(w: W, buffer: BufferType, alloc: Alloc, q: u32, lgwin: u32) -> Self {
38        CompressorWriterCustomAlloc::<W, BufferType, Alloc>(CompressorWriterCustomIo::<
39            Error,
40            IntoIoWriter<W>,
41            BufferType,
42            Alloc,
43        >::new(
44            IntoIoWriter::<W>(w),
45            buffer,
46            alloc,
47            Error::new(ErrorKind::InvalidData, "Invalid Data"),
48            Error::new(ErrorKind::WriteZero, "No room in output."),
49            q,
50            lgwin,
51        ))
52    }
53
54    pub fn get_ref(&self) -> &W {
55        &self.0.get_ref().0
56    }
57    pub fn get_mut(&mut self) -> &mut W {
58        &mut self.0.get_mut().0
59    }
60    pub fn into_inner(self) -> W {
61        self.0.into_inner().0
62    }
63}
64
65#[cfg(feature = "std")]
66impl<W: Write, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc> Write
67    for CompressorWriterCustomAlloc<W, BufferType, Alloc>
68{
69    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
70        self.0.write(buf)
71    }
72    fn flush(&mut self) -> Result<(), Error> {
73        self.0.flush()
74    }
75}
76
77#[cfg(feature = "std")]
78pub struct CompressorWriter<W: Write>(
79    CompressorWriterCustomAlloc<
80        W,
81        <StandardAlloc as Allocator<u8>>::AllocatedMemory,
82        StandardAlloc,
83    >,
84);
85
86#[cfg(feature = "std")]
87impl<W: Write> CompressorWriter<W> {
88    pub fn new(w: W, buffer_size: usize, q: u32, lgwin: u32) -> Self {
89        let mut alloc = StandardAlloc::default();
90        let buffer = allocate::<u8, _>(
91            &mut alloc,
92            if buffer_size == 0 { 4096 } else { buffer_size },
93        );
94        CompressorWriter::<W>(CompressorWriterCustomAlloc::new(w, buffer, alloc, q, lgwin))
95    }
96
97    pub fn with_params(w: W, buffer_size: usize, params: &BrotliEncoderParams) -> Self {
98        let mut writer = Self::new(w, buffer_size, params.quality as u32, params.lgwin as u32);
99        (writer.0).0.state.params = params.clone();
100        writer
101    }
102
103    pub fn get_ref(&self) -> &W {
104        self.0.get_ref()
105    }
106    pub fn get_mut(&mut self) -> &mut W {
107        self.0.get_mut()
108    }
109    pub fn into_inner(self) -> W {
110        self.0.into_inner()
111    }
112}
113
114#[cfg(feature = "std")]
115impl<W: Write> Write for CompressorWriter<W> {
116    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
117        self.0.write(buf)
118    }
119    fn flush(&mut self) -> Result<(), Error> {
120        self.0.flush()
121    }
122}
123
124pub struct CompressorWriterCustomIo<
125    ErrType,
126    W: CustomWrite<ErrType>,
127    BufferType: SliceWrapperMut<u8>,
128    Alloc: BrotliAlloc,
129> {
130    output_buffer: BufferType,
131    total_out: Option<usize>,
132    output: Option<W>,
133    error_if_invalid_data: Option<ErrType>,
134    state: BrotliEncoderStateStruct<Alloc>,
135    error_if_zero_bytes_written: Option<ErrType>,
136}
137pub fn write_all<ErrType, W: CustomWrite<ErrType>, ErrMaker: FnMut() -> Option<ErrType>>(
138    writer: &mut W,
139    mut buf: &[u8],
140    mut error_to_return_if_zero_bytes_written: ErrMaker,
141) -> Result<(), ErrType> {
142    while !buf.is_empty() {
143        match writer.write(buf) {
144            Ok(bytes_written) => {
145                if bytes_written != 0 {
146                    buf = &buf[bytes_written..]
147                } else {
148                    if let Some(err) = error_to_return_if_zero_bytes_written() {
149                        return Err(err);
150                    } else {
151                        return Ok(());
152                    }
153                }
154            }
155            Err(e) => return Err(e),
156        }
157    }
158    Ok(())
159}
160impl<ErrType, W: CustomWrite<ErrType>, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc>
161    CompressorWriterCustomIo<ErrType, W, BufferType, Alloc>
162{
163    pub fn new(
164        w: W,
165        buffer: BufferType,
166        alloc: Alloc,
167        invalid_data_error_type: ErrType,
168        error_if_zero_bytes_written: ErrType,
169        q: u32,
170        lgwin: u32,
171    ) -> Self {
172        let mut ret = CompressorWriterCustomIo {
173            output_buffer: buffer,
174            total_out: Some(0),
175            output: Some(w),
176            state: BrotliEncoderStateStruct::new(alloc),
177            error_if_invalid_data: Some(invalid_data_error_type),
178            error_if_zero_bytes_written: Some(error_if_zero_bytes_written),
179        };
180        ret.state
181            .set_parameter(BrotliEncoderParameter::BROTLI_PARAM_QUALITY, q);
182        ret.state
183            .set_parameter(BrotliEncoderParameter::BROTLI_PARAM_LGWIN, lgwin);
184
185        ret
186    }
187    fn flush_or_close(&mut self, op: BrotliEncoderOperation) -> Result<(), ErrType> {
188        let mut nop_callback =
189            |_data: &mut interface::PredictionModeContextMap<interface::InputReferenceMut>,
190             _cmds: &mut [interface::StaticCommand],
191             _mb: interface::InputPair,
192             _mfv: &mut Alloc| ();
193
194        loop {
195            let mut avail_in: usize = 0;
196            let mut input_offset: usize = 0;
197            let mut avail_out: usize = self.output_buffer.slice_mut().len();
198            let mut output_offset: usize = 0;
199            let ret = self.state.compress_stream(
200                op,
201                &mut avail_in,
202                &[],
203                &mut input_offset,
204                &mut avail_out,
205                self.output_buffer.slice_mut(),
206                &mut output_offset,
207                &mut self.total_out,
208                &mut nop_callback,
209            );
210            if output_offset > 0 {
211                let zero_err = &mut self.error_if_zero_bytes_written;
212                let fallback = &mut self.error_if_invalid_data;
213                match write_all(
214                    self.output.as_mut().unwrap(),
215                    &self.output_buffer.slice_mut()[..output_offset],
216                    || {
217                        if let Some(err) = zero_err.take() {
218                            return Some(err);
219                        }
220                        fallback.take()
221                    },
222                ) {
223                    Ok(_) => {}
224                    Err(e) => return Err(e),
225                }
226            }
227            if !ret {
228                return Err(self.error_if_invalid_data.take().unwrap());
229            }
230            if let BrotliEncoderOperation::BROTLI_OPERATION_FLUSH = op {
231                if self.state.has_more_output() {
232                    continue;
233                }
234                return Ok(());
235            }
236            if self.state.is_finished() {
237                return Ok(());
238            }
239        }
240    }
241
242    pub fn get_ref(&self) -> &W {
243        self.output.as_ref().unwrap()
244    }
245    pub fn get_mut(&mut self) -> &mut W {
246        self.output.as_mut().unwrap()
247    }
248    pub fn into_inner(mut self) -> W {
249        match self.flush_or_close(BrotliEncoderOperation::BROTLI_OPERATION_FINISH) {
250            Ok(_) => {}
251            Err(_) => {}
252        }
253        self.output.take().unwrap()
254    }
255}
256
257impl<ErrType, W: CustomWrite<ErrType>, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc> Drop
258    for CompressorWriterCustomIo<ErrType, W, BufferType, Alloc>
259{
260    fn drop(&mut self) {
261        if self.output.is_some() {
262            match self.flush_or_close(BrotliEncoderOperation::BROTLI_OPERATION_FINISH) {
263                Ok(_) => {}
264                Err(_) => {}
265            }
266        }
267        BrotliEncoderDestroyInstance(&mut self.state);
268    }
269}
270impl<ErrType, W: CustomWrite<ErrType>, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc>
271    CustomWrite<ErrType> for CompressorWriterCustomIo<ErrType, W, BufferType, Alloc>
272{
273    fn write(&mut self, buf: &[u8]) -> Result<usize, ErrType> {
274        let mut nop_callback =
275            |_data: &mut interface::PredictionModeContextMap<interface::InputReferenceMut>,
276             _cmds: &mut [interface::StaticCommand],
277             _mb: interface::InputPair,
278             _mfv: &mut Alloc| ();
279        let mut avail_in = buf.len();
280        let mut input_offset: usize = 0;
281        while avail_in != 0 {
282            let mut output_offset = 0;
283            let mut avail_out = self.output_buffer.slice_mut().len();
284            let ret = self.state.compress_stream(
285                BrotliEncoderOperation::BROTLI_OPERATION_PROCESS,
286                &mut avail_in,
287                buf,
288                &mut input_offset,
289                &mut avail_out,
290                self.output_buffer.slice_mut(),
291                &mut output_offset,
292                &mut self.total_out,
293                &mut nop_callback,
294            );
295            if output_offset > 0 {
296                let zero_err = &mut self.error_if_zero_bytes_written;
297                let fallback = &mut self.error_if_invalid_data;
298                match write_all(
299                    self.output.as_mut().unwrap(),
300                    &self.output_buffer.slice_mut()[..output_offset],
301                    || {
302                        if let Some(err) = zero_err.take() {
303                            return Some(err);
304                        }
305                        fallback.take()
306                    },
307                ) {
308                    Ok(_) => {}
309                    Err(e) => return Err(e),
310                }
311            }
312            if !ret {
313                return Err(self.error_if_invalid_data.take().unwrap());
314            }
315        }
316        Ok(buf.len())
317    }
318    fn flush(&mut self) -> Result<(), ErrType> {
319        match self.flush_or_close(BrotliEncoderOperation::BROTLI_OPERATION_FLUSH) {
320            Ok(_) => {}
321            Err(e) => return Err(e),
322        }
323        self.output.as_mut().unwrap().flush()
324    }
325}