Skip to main content

brotli/enc/
reader.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, Read};
8
9#[cfg(feature = "std")]
10pub use alloc_stdlib::StandardAlloc;
11use brotli_decompressor::CustomRead;
12#[cfg(feature = "std")]
13pub use brotli_decompressor::{IntoIoReader, IoReaderWrapper, 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 CompressorReaderCustomAlloc<R: Read, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc>(
28    CompressorReaderCustomIo<io::Error, IntoIoReader<R>, BufferType, Alloc>,
29);
30
31#[cfg(feature = "std")]
32impl<R: Read, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc>
33    CompressorReaderCustomAlloc<R, BufferType, Alloc>
34{
35    pub fn new(r: R, buffer: BufferType, alloc: Alloc, q: u32, lgwin: u32) -> Self {
36        CompressorReaderCustomAlloc::<R, BufferType, Alloc>(CompressorReaderCustomIo::<
37            Error,
38            IntoIoReader<R>,
39            BufferType,
40            Alloc,
41        >::new(
42            IntoIoReader::<R>(r),
43            buffer,
44            alloc,
45            Error::new(ErrorKind::InvalidData, "Invalid Data"),
46            q,
47            lgwin,
48        ))
49    }
50
51    pub fn get_ref(&self) -> &R {
52        &self.0.get_ref().0
53    }
54    pub fn into_inner(self) -> R {
55        self.0.into_inner().0
56    }
57}
58
59#[cfg(feature = "std")]
60impl<R: Read, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc> Read
61    for CompressorReaderCustomAlloc<R, BufferType, Alloc>
62{
63    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
64        self.0.read(buf)
65    }
66}
67
68#[cfg(feature = "std")]
69pub struct CompressorReader<R: Read>(
70    CompressorReaderCustomAlloc<
71        R,
72        <StandardAlloc as Allocator<u8>>::AllocatedMemory,
73        StandardAlloc,
74    >,
75);
76
77#[cfg(feature = "std")]
78impl<R: Read> CompressorReader<R> {
79    pub fn new(r: R, buffer_size: usize, q: u32, lgwin: u32) -> Self {
80        let mut alloc = StandardAlloc::default();
81        let buffer = allocate::<u8, _>(
82            &mut alloc,
83            if buffer_size == 0 { 4096 } else { buffer_size },
84        );
85        CompressorReader::<R>(CompressorReaderCustomAlloc::new(r, buffer, alloc, q, lgwin))
86    }
87
88    pub fn with_params(r: R, buffer_size: usize, params: &BrotliEncoderParams) -> Self {
89        let mut reader = Self::new(r, buffer_size, params.quality as u32, params.lgwin as u32);
90        (reader.0).0.state.0.params = params.clone();
91        reader
92    }
93
94    pub fn get_ref(&self) -> &R {
95        self.0.get_ref()
96    }
97    pub fn into_inner(self) -> R {
98        self.0.into_inner()
99    }
100}
101
102#[cfg(feature = "std")]
103impl<R: Read> Read for CompressorReader<R> {
104    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
105        self.0.read(buf)
106    }
107}
108
109pub struct CompressorReaderCustomIo<
110    ErrType,
111    R: CustomRead<ErrType>,
112    BufferType: SliceWrapperMut<u8>,
113    Alloc: BrotliAlloc,
114> {
115    input_buffer: BufferType,
116    total_out: Option<usize>,
117    input_offset: usize,
118    input_len: usize,
119    input: R,
120    input_eof: bool,
121    error_if_invalid_data: Option<ErrType>,
122    state: StateWrapper<Alloc>,
123}
124struct StateWrapper<Alloc: BrotliAlloc>(BrotliEncoderStateStruct<Alloc>);
125
126impl<Alloc: BrotliAlloc> Drop for StateWrapper<Alloc> {
127    fn drop(&mut self) {
128        BrotliEncoderDestroyInstance(&mut self.0);
129    }
130}
131
132impl<ErrType, R: CustomRead<ErrType>, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc>
133    CompressorReaderCustomIo<ErrType, R, BufferType, Alloc>
134{
135    pub fn new(
136        r: R,
137        buffer: BufferType,
138        alloc: Alloc,
139        invalid_data_error_type: ErrType,
140        q: u32,
141        lgwin: u32,
142    ) -> Self {
143        let mut ret = CompressorReaderCustomIo {
144            input_buffer: buffer,
145            total_out: Some(0),
146            input_offset: 0,
147            input_len: 0,
148            input_eof: false,
149            input: r,
150            state: StateWrapper(BrotliEncoderStateStruct::new(alloc)),
151            error_if_invalid_data: Some(invalid_data_error_type),
152        };
153        ret.state
154            .0
155            .set_parameter(BrotliEncoderParameter::BROTLI_PARAM_QUALITY, q);
156        ret.state
157            .0
158            .set_parameter(BrotliEncoderParameter::BROTLI_PARAM_LGWIN, lgwin);
159
160        ret
161    }
162    pub fn copy_to_front(&mut self) {
163        let avail_in = self.input_len - self.input_offset;
164        if self.input_offset == self.input_buffer.slice_mut().len() {
165            self.input_offset = 0;
166            self.input_len = 0;
167        } else if self.input_offset + 256 > self.input_buffer.slice_mut().len()
168            && avail_in < self.input_offset
169        {
170            let (first, second) = self
171                .input_buffer
172                .slice_mut()
173                .split_at_mut(self.input_offset);
174            first[0..avail_in].clone_from_slice(&second[0..avail_in]);
175            self.input_len -= self.input_offset;
176            self.input_offset = 0;
177        }
178    }
179    pub fn into_inner(self) -> R {
180        match self {
181            CompressorReaderCustomIo {
182                input_buffer: _ib,
183                total_out: _to,
184                input_offset: _io,
185                input_len: _len,
186                input,
187                input_eof: _ieof,
188                error_if_invalid_data: _eiid,
189                state: _state,
190            } => input,
191        }
192    }
193    pub fn get_ref(&self) -> &R {
194        &self.input
195    }
196}
197impl<ErrType, R: CustomRead<ErrType>, BufferType: SliceWrapperMut<u8>, Alloc: BrotliAlloc>
198    CustomRead<ErrType> for CompressorReaderCustomIo<ErrType, R, BufferType, Alloc>
199{
200    fn read(&mut self, buf: &mut [u8]) -> Result<usize, ErrType> {
201        let mut nop_callback =
202            |_data: &mut interface::PredictionModeContextMap<interface::InputReferenceMut>,
203             _cmds: &mut [interface::StaticCommand],
204             _mb: interface::InputPair,
205             _mfv: &mut Alloc| ();
206        let mut output_offset: usize = 0;
207        let mut avail_out = buf.len();
208        let mut avail_in = self.input_len - self.input_offset;
209        while output_offset == 0 {
210            if self.input_len < self.input_buffer.slice_mut().len() && !self.input_eof {
211                match self
212                    .input
213                    .read(&mut self.input_buffer.slice_mut()[self.input_len..])
214                {
215                    Err(e) => return Err(e),
216                    Ok(size) => {
217                        if size == 0 {
218                            self.input_eof = true;
219                        } else {
220                            self.input_len += size;
221                            avail_in = self.input_len - self.input_offset;
222                        }
223                    }
224                }
225            }
226            let op: BrotliEncoderOperation;
227            if avail_in == 0 {
228                op = BrotliEncoderOperation::BROTLI_OPERATION_FINISH;
229            } else {
230                op = BrotliEncoderOperation::BROTLI_OPERATION_PROCESS;
231            }
232            let ret = self.state.0.compress_stream(
233                op,
234                &mut avail_in,
235                self.input_buffer.slice_mut(),
236                &mut self.input_offset,
237                &mut avail_out,
238                buf,
239                &mut output_offset,
240                &mut self.total_out,
241                &mut nop_callback,
242            );
243            if avail_in == 0 {
244                self.copy_to_front();
245            }
246            if !ret {
247                return Err(self.error_if_invalid_data.take().unwrap());
248            }
249            if self.state.0.is_finished() {
250                break;
251            }
252        }
253        Ok(output_offset)
254    }
255}