Skip to main content

brotli_decompressor/
reader.rs

1#[cfg(feature="std")]
2use std::io::{self, Error, ErrorKind, Read};
3#[cfg(feature="std")]
4pub use alloc_stdlib::StandardAlloc;
5#[cfg(all(feature="unsafe",feature="std"))]
6pub use alloc_stdlib::HeapAlloc;
7pub use huffman::{HuffmanCode, HuffmanTreeGroup};
8pub use state::BrotliState;
9use state::BrotliDecoderParameter;
10// use io_wrappers::write_all;
11pub use io_wrappers::{CustomRead, CustomWrite};
12#[cfg(feature="std")]
13pub use io_wrappers::{IntoIoReader, IoReaderWrapper, IoWriterWrapper};
14pub use super::decode::{BrotliDecompressStream, BrotliResult};
15pub use alloc::{AllocatedStackMemory, Allocator, SliceWrapper, SliceWrapperMut, StackAllocator};
16
17#[cfg(feature="std")]
18pub struct DecompressorCustomAlloc<R: Read,
19     BufferType : SliceWrapperMut<u8>,
20     AllocU8 : Allocator<u8>,
21     AllocU32 : Allocator<u32>,
22     AllocHC : Allocator<HuffmanCode> >(DecompressorCustomIo<io::Error,
23                                                             IntoIoReader<R>,
24                                                             BufferType,
25                                                             AllocU8, AllocU32, AllocHC>);
26
27
28#[cfg(feature="std")]
29impl<R: Read,
30     BufferType : SliceWrapperMut<u8>,
31     AllocU8,
32     AllocU32,
33     AllocHC> DecompressorCustomAlloc<R, BufferType, AllocU8, AllocU32, AllocHC>
34 where AllocU8 : Allocator<u8>, AllocU32 : Allocator<u32>, AllocHC : Allocator<HuffmanCode>
35    {
36
37    pub fn new(r: R, buffer : BufferType,
38               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC) -> Self {
39        DecompressorCustomAlloc::<R, BufferType, AllocU8, AllocU32, AllocHC>(
40          DecompressorCustomIo::<Error,
41                                 IntoIoReader<R>,
42                                 BufferType,
43                                 AllocU8, AllocU32, AllocHC>::new(IntoIoReader::<R>(r),
44                                                                  buffer,
45                                                                  alloc_u8, alloc_u32, alloc_hc,
46                                                                  Error::new(ErrorKind::InvalidData,
47                                                                             "Invalid Data")))
48    }
49
50    pub fn new_with_custom_dictionary(r: R, buffer : BufferType,
51               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC,
52               dict: AllocU8::AllocatedMemory) -> Self {
53        DecompressorCustomAlloc::<R, BufferType, AllocU8, AllocU32, AllocHC>(
54          DecompressorCustomIo::<Error,
55                                 IntoIoReader<R>,
56                                 BufferType,
57                                 AllocU8, AllocU32, AllocHC>::new_with_custom_dictionary(IntoIoReader::<R>(r),
58                                                                                   buffer,
59                                                                                   alloc_u8, alloc_u32, alloc_hc,
60                                                                                   dict,
61                                                                                   Error::new(ErrorKind::InvalidData,
62                                                                                              "Invalid Data")))
63    }
64
65    pub fn attach_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
66      self.0.attach_dictionary(dict)
67    }
68    pub fn attach_serialized_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
69      self.0.attach_serialized_dictionary(dict)
70    }
71    pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
72      self.0.set_parameter(param, value)
73    }
74    pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
75      self.0.set_initial_ring_buffer_size(size)
76    }
77
78    pub fn get_ref(&self) -> &R {
79      &self.0.get_ref().0
80    }
81    pub fn get_mut(&mut self) -> &mut R {
82      &mut self.0.get_mut().0
83    }
84    pub fn into_inner(self) -> R {
85      self.0.into_inner().0
86    }
87}
88#[cfg(feature="std")]
89impl<R: Read,
90     BufferType : SliceWrapperMut<u8>,
91     AllocU8 : Allocator<u8>,
92     AllocU32 : Allocator<u32>,
93     AllocHC : Allocator<HuffmanCode> > Read for DecompressorCustomAlloc<R,
94                                                                         BufferType,
95                                                                         AllocU8,
96                                                                         AllocU32,
97                                                                         AllocHC> {
98  	fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
99       self.0.read(buf)
100    }
101}
102
103
104#[cfg(not(any(feature="unsafe", not(feature="std"))))]
105pub struct Decompressor<R: Read>(DecompressorCustomAlloc<R,
106                                                         <StandardAlloc
107                                                          as Allocator<u8>>::AllocatedMemory,
108                                                         StandardAlloc,
109                                                         StandardAlloc,
110                                                         StandardAlloc>);
111
112
113#[cfg(not(any(feature="unsafe", not(feature="std"))))]
114impl<R: Read> Decompressor<R> {
115  pub fn new(r: R, buffer_size: usize) -> Self {
116     let dict = <StandardAlloc as Allocator<u8>>::AllocatedMemory::default();
117     Self::new_with_custom_dict(r, buffer_size, dict)
118  }
119  pub fn new_with_custom_dict(r: R, buffer_size: usize, dict: <StandardAlloc as Allocator<u8>>::AllocatedMemory) -> Self {
120    let mut alloc = StandardAlloc::default();
121    let buffer = <StandardAlloc as Allocator<u8>>::alloc_cell(&mut alloc, if buffer_size == 0 {4096} else {buffer_size});
122    Decompressor::<R>(DecompressorCustomAlloc::<R,
123                                                <StandardAlloc
124                                                 as Allocator<u8>>::AllocatedMemory,
125                                                StandardAlloc,
126                                                StandardAlloc,
127                                                StandardAlloc>::new_with_custom_dictionary(r,
128                                                                              buffer,
129                                                                              alloc,
130                                                                              StandardAlloc::default(),
131                                                                              StandardAlloc::default(),
132                                                                              dict))
133  }
134
135  // Attaches an additional raw LZ77 prefix dictionary; only allowed before
136  // the first read. Returns false if the dictionary could not be attached.
137  pub fn attach_dictionary(&mut self, dict: <StandardAlloc as Allocator<u8>>::AllocatedMemory) -> bool {
138    self.0.attach_dictionary(dict)
139  }
140
141  // Attaches a serialized shared dictionary (magic 0x91 0x00, may contain an
142  // LZ77 prefix dictionary and custom word/transform lists); only allowed
143  // before the first read.
144  pub fn attach_serialized_dictionary(&mut self, dict: <StandardAlloc as Allocator<u8>>::AllocatedMemory) -> bool {
145    self.0.attach_serialized_dictionary(dict)
146  }
147
148  // Sets a decoder parameter (see BrotliState::set_parameter); only allowed
149  // before the first read.
150  pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
151    self.0.set_parameter(param, value)
152  }
153
154  // Sets the smallest ring buffer the decoder starts from (see
155  // BrotliState::set_initial_ring_buffer_size); only allowed before the first
156  // read.
157  pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
158    self.0.set_initial_ring_buffer_size(size)
159  }
160
161  pub fn get_ref(&self) -> &R {
162    &self.0.get_ref()
163  }
164  pub fn get_mut(&mut self) -> &mut R {
165    &mut ((self.0).0).get_mut().0
166  }
167  pub fn into_inner(self) -> R {
168    self.0.into_inner()
169  }
170}
171
172
173#[cfg(all(feature="unsafe", feature="std"))]
174pub struct Decompressor<R: Read>(DecompressorCustomAlloc<R,
175                                                         <HeapAlloc<u8>
176                                                          as Allocator<u8>>::AllocatedMemory,
177                                                         HeapAlloc<u8>,
178                                                         HeapAlloc<u32>,
179                                                         HeapAlloc<HuffmanCode> >);
180
181
182#[cfg(all(feature="unsafe", feature="std"))]
183impl<R: Read> Decompressor<R> {
184  pub fn new(r: R, buffer_size: usize) -> Self {
185     let dict = <HeapAlloc<u8> as Allocator<u8>>::AllocatedMemory::default();
186     Self::new_with_custom_dictionary(r, buffer_size, dict)
187  }
188  pub fn new_with_custom_dictionary(r: R, buffer_size: usize, dict: <HeapAlloc<u8>
189                                                 as Allocator<u8>>::AllocatedMemory) -> Self {
190    let mut alloc_u8 = HeapAlloc::<u8>::new(0);
191    let buffer = alloc_u8.alloc_cell(if buffer_size == 0 {4096} else {buffer_size});
192    let alloc_u32 = HeapAlloc::<u32>::new(0);
193    let alloc_hc = HeapAlloc::<HuffmanCode>::new(HuffmanCode{
194        bits:0, value: 0,
195    });
196    Decompressor::<R>(DecompressorCustomAlloc::<R,
197                                                <HeapAlloc<u8>
198                                                 as Allocator<u8>>::AllocatedMemory,
199                                                HeapAlloc<u8>,
200                                                HeapAlloc<u32>,
201                                                HeapAlloc<HuffmanCode> >
202      ::new_with_custom_dictionary(r, buffer, alloc_u8, alloc_u32, alloc_hc, dict))
203  }
204
205  // Attaches an additional raw LZ77 prefix dictionary; only allowed before
206  // the first read. Returns false if the dictionary could not be attached.
207  pub fn attach_dictionary(&mut self, dict: <HeapAlloc<u8> as Allocator<u8>>::AllocatedMemory) -> bool {
208    self.0.attach_dictionary(dict)
209  }
210
211  // Attaches a serialized shared dictionary (magic 0x91 0x00, may contain an
212  // LZ77 prefix dictionary and custom word/transform lists); only allowed
213  // before the first read.
214  pub fn attach_serialized_dictionary(&mut self, dict: <HeapAlloc<u8> as Allocator<u8>>::AllocatedMemory) -> bool {
215    self.0.attach_serialized_dictionary(dict)
216  }
217
218  // Sets a decoder parameter (see BrotliState::set_parameter); only allowed
219  // before the first read.
220  pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
221    self.0.set_parameter(param, value)
222  }
223
224  // Sets the smallest ring buffer the decoder starts from (see
225  // BrotliState::set_initial_ring_buffer_size); only allowed before the first
226  // read.
227  pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
228    self.0.set_initial_ring_buffer_size(size)
229  }
230
231  pub fn get_ref(&self) -> &R {
232    self.0.get_ref()
233  }
234  pub fn get_mut(&mut self) -> &mut R {
235    &mut (self.0).0.get_mut().0
236  }
237  pub fn into_inner(self) -> R {
238    self.0.into_inner()
239  }
240}
241
242
243#[cfg(feature="std")]
244impl<R: Read> Read for Decompressor<R> {
245  fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
246    self.0.read(buf)
247  }
248}
249
250pub struct DecompressorCustomIo<ErrType,
251                                R: CustomRead<ErrType>,
252                                BufferType: SliceWrapperMut<u8>,
253                                AllocU8: Allocator<u8>,
254                                AllocU32: Allocator<u32>,
255                                AllocHC: Allocator<HuffmanCode>>
256{
257  input_buffer: BufferType,
258  total_out: usize,
259  input_offset: usize,
260  input_len: usize,
261  input: R,
262  error_if_invalid_data: Option<ErrType>,
263  state: BrotliState<AllocU8, AllocU32, AllocHC>,
264  done: bool,
265}
266
267impl<ErrType,
268     R: CustomRead<ErrType>,
269     BufferType : SliceWrapperMut<u8>,
270     AllocU8,
271     AllocU32,
272     AllocHC> DecompressorCustomIo<ErrType, R, BufferType, AllocU8, AllocU32, AllocHC>
273 where AllocU8 : Allocator<u8>, AllocU32 : Allocator<u32>, AllocHC : Allocator<HuffmanCode>
274{
275
276    pub fn new(r: R, buffer : BufferType,
277               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC,
278               invalid_data_error_type : ErrType) -> Self {
279     let dict = AllocU8::AllocatedMemory::default();
280     Self::new_with_custom_dictionary(r, buffer, alloc_u8, alloc_u32, alloc_hc, dict, invalid_data_error_type)
281    }
282    pub fn new_with_custom_dictionary(r: R, buffer : BufferType,
283               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC,
284               dict: AllocU8::AllocatedMemory,
285               invalid_data_error_type : ErrType) -> Self {
286        DecompressorCustomIo::<ErrType, R, BufferType, AllocU8, AllocU32, AllocHC>{
287            input_buffer : buffer,
288            total_out : 0,
289            input_offset : 0,
290            input_len : 0,
291            input: r,
292            state : BrotliState::new_with_custom_dictionary(alloc_u8,
293                                     alloc_u32,
294                                     alloc_hc,
295                                     dict),
296            error_if_invalid_data : Some(invalid_data_error_type),
297            done: false,
298        }
299    }
300
301    // Attaches an additional raw LZ77 prefix dictionary; only allowed before
302    // the first read. Returns false if the dictionary could not be attached.
303    pub fn attach_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
304      self.state.attach_dictionary(dict)
305    }
306
307    // Attaches a serialized shared dictionary (magic 0x91 0x00, may contain
308    // an LZ77 prefix dictionary and custom word/transform lists); only
309    // allowed before the first read.
310    pub fn attach_serialized_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
311      self.state.attach_serialized_dictionary(dict)
312    }
313
314    // Sets a decoder parameter (see BrotliState::set_parameter); only
315    // allowed before the first read.
316    pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
317      self.state.set_parameter(param, value)
318    }
319
320    // Sets the smallest ring buffer the decoder starts from (see
321    // BrotliState::set_initial_ring_buffer_size); only allowed before the
322    // first read.
323    pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
324      self.state.set_initial_ring_buffer_size(size)
325    }
326
327    pub fn get_ref(&self) -> &R {
328      &self.input
329    }
330    pub fn get_mut(&mut self) -> &mut R {
331      &mut self.input
332    }
333    pub fn into_inner(self) -> R {
334      match self {
335        DecompressorCustomIo {
336          input_buffer: _ib,
337          total_out: _to,
338          state: _state,
339          input_offset: _io,
340          input_len: _il,
341          error_if_invalid_data:_eiid,
342          input,
343          done: _done,
344        } =>{
345          input
346        }
347    }
348    }
349
350    pub fn copy_to_front(&mut self) {
351        let avail_in = self.input_len - self.input_offset;
352        if self.input_offset == self.input_buffer.slice_mut().len() {
353            self.input_offset = 0;
354            self.input_len = 0;
355        } else if self.input_offset + 256 > self.input_buffer.slice_mut().len() && avail_in < self.input_offset {
356            let (first, second) = self.input_buffer.slice_mut().split_at_mut(self.input_offset);
357            self.input_len -= self.input_offset;
358            first[0..avail_in].clone_from_slice(&second[0..avail_in]);
359            self.input_offset = 0;
360        }
361    }
362}
363
364impl<ErrType,
365     R: CustomRead<ErrType>,
366     BufferType : SliceWrapperMut<u8>,
367     AllocU8 : Allocator<u8>,
368     AllocU32 : Allocator<u32>,
369     AllocHC : Allocator<HuffmanCode> > CustomRead<ErrType> for DecompressorCustomIo<ErrType,
370                                                                                     R,
371                                                                                     BufferType,
372                                                                                     AllocU8,
373                                                                                     AllocU32,
374                                                                                     AllocHC> {
375  /// This variant of read will return Ok(number of bytes read) until the file
376  /// Is completed at which point it will return Ok(0).
377  /// However if there are additional unconsumed bytes in the buffer, it will
378  /// return Err(InvalidData) at that point. Otherwise it will keep returning
379  /// Ok(0).
380  ///
381  /// # Arguments
382  ///
383  /// * `buf` - The buffer to read into
384  ///
385  /// # Errors
386  ///
387  /// Returns Ok(0) if the file has been fully decompressed.
388  /// If the file has been fully decompressed but there are additional
389  /// non-brotli bytes in the buffer, then return an InvalidData error.
390  /// Also upstream errors from the reader are returned.
391  fn read(&mut self, buf: &mut [u8]) -> Result<usize, ErrType > {
392    let mut output_offset : usize = 0;
393    let mut avail_out = buf.len() - output_offset;
394    let mut avail_in = self.input_len - self.input_offset;
395    while avail_out == buf.len() {
396      match BrotliDecompressStream(&mut avail_in,
397                                   &mut self.input_offset,
398                                   &self.input_buffer.slice_mut()[..],
399                                   &mut avail_out,
400                                   &mut output_offset,
401                                   buf,
402                                   &mut self.total_out,
403                                   &mut self.state) {
404        BrotliResult::NeedsMoreInput => {
405          self.copy_to_front();
406          if output_offset != 0 {
407            // The decompressor successfully decoded some bytes, but still requires more
408            // we do not wish to risk self.input.read returning an error, so instead we
409            // opt to return what we have and do not invoke the read trait method
410            return Ok(output_offset);
411          }
412          match self.input.read(&mut self.input_buffer.slice_mut()[self.input_len..]) {
413            Err(e) => {
414              return Err(e);
415            },
416            Ok(size) => if size == 0 {
417              return self.error_if_invalid_data.take().map(|e| Err(e)).unwrap_or(Ok(0));
418            }else {
419              self.input_len += size;
420              avail_in = self.input_len - self.input_offset;
421            },
422          }
423        },
424        BrotliResult::NeedsMoreOutput => {
425          break;
426        },
427        BrotliResult::ResultSuccess => {
428            if output_offset == 0 {
429                if !self.done {
430                    self.done = true;
431                } else if self.input_len != self.input_offset {
432                    // Did not consume entire input; report error.
433                    return self.error_if_invalid_data.take().map(|e| Err(e)).unwrap_or(Ok(output_offset));
434                }
435            }
436            return Ok(output_offset);
437        }
438        BrotliResult::ResultFailure => return self.error_if_invalid_data.take().map(|e| Err(e)).unwrap_or(Ok(0)),
439      }
440    }
441    Ok(output_offset)
442  }
443}
444
445#[cfg(feature="std")]
446#[test]
447fn test_no_vanishing_bytes() {
448    use std::string::ToString;
449
450    // Output from this command:
451    let compressed_with_extra = b"\x8f\x02\x80\x68\x65\x6c\x6c\x6f\x0a\x03\x67\x6f\x6f\x64\x62\x79\x65\x0a";
452    // Make sure that read_to_string returns the data.
453    let cursor = std::io::Cursor::new(compressed_with_extra);
454    let mut reader = super::Decompressor::new(cursor, 8000);
455    let mut out = std::string::String::new();
456    std::io::Read::read_to_string(&mut reader, &mut out).unwrap();
457    assert_eq!(out, "hello\n");
458
459    // However you can call read extra times to make sure there's no data.
460    let cursor = std::io::Cursor::new(compressed_with_extra);
461    let mut reader = super::Decompressor::new(cursor, 8000);
462    let mut data = std::vec::Vec::<u8>::default();
463    loop {
464        let mut buf = [0u8;5];
465        let offset = reader.read(&mut buf).unwrap();
466        if offset == 0 {
467            break;
468        }
469        data.extend_from_slice(&buf[..offset]);
470    }
471    assert_eq!(
472        &data,
473        &['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8, '\n' as u8]);
474
475    // But calling read, one last time, results in an error because there
476    // were leftover bytes in the buffer.
477    let mut buf = [0u8;5];
478    assert_eq!(reader.read(&mut buf).unwrap_err().kind(),
479               io::ErrorKind::InvalidData);
480    data.clear();
481
482
483}
484
485#[cfg(feature="std")]
486#[test]
487fn test_repeated_read_returns_zero() {
488    use std::string::ToString;
489
490    // Output from this command:
491    let compressed_without_extra = b"\x8f\x02\x80\x68\x65\x6c\x6c\x6f\x0a\x03";
492    // Make sure that read_to_string returns the data.
493    let cursor = std::io::Cursor::new(compressed_without_extra);
494    let mut reader = super::Decompressor::new(cursor, 8000);
495    let mut out = std::string::String::new();
496    std::io::Read::read_to_string(&mut reader, &mut out).unwrap();
497    assert_eq!(out, "hello\n");
498
499    // However you can call read extra times to make sure there's no data.
500    let cursor = std::io::Cursor::new(compressed_without_extra);
501    let mut reader = super::Decompressor::new(cursor, 8000);
502    let mut data = std::vec::Vec::<u8>::default();
503    loop {
504        let mut buf = [0u8;5];
505        let offset = reader.read(&mut buf).unwrap();
506        if offset == 0 {
507            break;
508        }
509        data.extend_from_slice(&buf[..offset]);
510    }
511    assert_eq!(&data, &['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8, '\n' as u8]);
512    let mut buf = [0u8;5];
513    assert_eq!(reader.read(&mut buf).unwrap(), 0);
514    data.clear();
515
516
517}
518