Skip to main content

brotli_decompressor/
writer.rs

1use core;
2#[cfg(feature="std")]
3use std::io::{self, Error, ErrorKind, Write};
4#[cfg(feature="std")]
5pub use alloc_stdlib::StandardAlloc;
6#[cfg(all(feature="unsafe",feature="std"))]
7pub use alloc_stdlib::HeapAlloc;
8pub use huffman::{HuffmanCode, HuffmanTreeGroup};
9pub use state::BrotliState;
10use state::BrotliDecoderParameter;
11// use io_wrappers::write_all;
12pub use io_wrappers::{CustomWrite};
13#[cfg(feature="std")]
14pub use io_wrappers::{IntoIoWriter, IoWriterWrapper};
15pub use super::decode::{BrotliDecompressStream, BrotliResult};
16pub use alloc::{AllocatedStackMemory, Allocator, SliceWrapper, SliceWrapperMut, StackAllocator};
17
18#[cfg(feature="std")]
19pub struct DecompressorWriterCustomAlloc<W: Write,
20     BufferType : SliceWrapperMut<u8>,
21     AllocU8 : Allocator<u8>,
22     AllocU32 : Allocator<u32>,
23     AllocHC : Allocator<HuffmanCode> >(DecompressorWriterCustomIo<io::Error,
24                                                             IntoIoWriter<W>,
25                                                             BufferType,
26                                                             AllocU8, AllocU32, AllocHC>);
27
28
29#[cfg(feature="std")]
30impl<W: Write,
31     BufferType : SliceWrapperMut<u8>,
32     AllocU8,
33     AllocU32,
34     AllocHC> DecompressorWriterCustomAlloc<W, BufferType, AllocU8, AllocU32, AllocHC>
35 where AllocU8 : Allocator<u8>, AllocU32 : Allocator<u32>, AllocHC : Allocator<HuffmanCode>
36    {
37    pub fn new(w: W, buffer : BufferType,
38               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC) -> Self {
39     let dict = AllocU8::AllocatedMemory::default();
40     Self::new_with_custom_dictionary(w, buffer, alloc_u8, alloc_u32, alloc_hc, dict)
41
42    }
43    pub fn new_with_custom_dictionary(w: W, buffer : BufferType,
44               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC, dict: AllocU8::AllocatedMemory) -> Self {
45        DecompressorWriterCustomAlloc::<W, BufferType, AllocU8, AllocU32, AllocHC>(
46          DecompressorWriterCustomIo::<Error,
47                                 IntoIoWriter<W>,
48                                 BufferType,
49                                 AllocU8, AllocU32, AllocHC>::new_with_custom_dictionary(IntoIoWriter::<W>(w),
50                                                                  buffer,
51                                                                  alloc_u8, alloc_u32, alloc_hc,
52                                                                  dict,
53                                                                  Error::new(ErrorKind::InvalidData,
54                                                                             "Invalid Data")))
55    }
56
57    pub fn attach_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
58      self.0.attach_dictionary(dict)
59    }
60    pub fn attach_serialized_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
61      self.0.attach_serialized_dictionary(dict)
62    }
63    pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
64      self.0.set_parameter(param, value)
65    }
66    pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
67      self.0.set_initial_ring_buffer_size(size)
68    }
69
70    pub fn get_ref(&self) -> &W {
71        &self.0.get_ref().0
72    }
73    pub fn get_mut(&mut self) -> &mut W {
74        &mut self.0.get_mut().0
75    }
76    pub fn into_inner(self) -> Result<W, W> {
77        match self.0.into_inner() {
78            Ok(w) => Ok(w.0),
79            Err(w) => Err(w.0),
80        }
81    }
82}
83#[cfg(feature="std")]
84impl<W: Write,
85     BufferType : SliceWrapperMut<u8>,
86     AllocU8 : Allocator<u8>,
87     AllocU32 : Allocator<u32>,
88     AllocHC : Allocator<HuffmanCode> > Write for DecompressorWriterCustomAlloc<W,
89                                                                         BufferType,
90                                                                         AllocU8,
91                                                                         AllocU32,
92                                                                         AllocHC> {
93  	fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
94       self.0.write(buf)
95    }
96  	fn flush(&mut self) -> Result<(), Error> {
97       self.0.flush()
98    }
99}
100
101#[cfg(feature="std")]
102impl<W: Write,
103     BufferType : SliceWrapperMut<u8>,
104     AllocU8 : Allocator<u8>,
105     AllocU32 : Allocator<u32>,
106     AllocHC : Allocator<HuffmanCode> > DecompressorWriterCustomAlloc<W,
107                                                                         BufferType,
108                                                                         AllocU8,
109                                                                         AllocU32,
110                                                                         AllocHC> {
111    pub fn close(&mut self) -> Result<(), Error>{
112        self.0.close()
113    }
114}
115
116
117#[cfg(not(any(feature="unsafe", not(feature="std"))))]
118pub struct DecompressorWriter<W: Write>(DecompressorWriterCustomAlloc<W,
119                                                         <StandardAlloc
120                                                          as Allocator<u8>>::AllocatedMemory,
121                                                         StandardAlloc,
122                                                         StandardAlloc,
123                                                         StandardAlloc>);
124
125
126#[cfg(not(any(feature="unsafe", not(feature="std"))))]
127impl<W: Write> DecompressorWriter<W> {
128  pub fn new(w: W, buffer_size: usize) -> Self {
129      Self::new_with_custom_dictionary(w, buffer_size, <StandardAlloc as Allocator<u8>>::AllocatedMemory::default())
130  }
131  pub fn new_with_custom_dictionary(w: W, buffer_size: usize, dict: <StandardAlloc as Allocator<u8>>::AllocatedMemory) -> Self {
132    let mut alloc = StandardAlloc::default();
133    let buffer = <StandardAlloc as Allocator<u8>>::alloc_cell(&mut alloc, if buffer_size == 0 {4096} else {buffer_size});
134    DecompressorWriter::<W>(DecompressorWriterCustomAlloc::<W,
135                                                <StandardAlloc
136                                                 as Allocator<u8>>::AllocatedMemory,
137                                                StandardAlloc,
138                                                StandardAlloc,
139                                                StandardAlloc>::new_with_custom_dictionary(w,
140                                                                              buffer,
141                                                                              alloc,
142                                                                              StandardAlloc::default(),
143                                                                              StandardAlloc::default(),
144                                                                              dict))
145  }
146
147  // Attaches an additional raw LZ77 prefix dictionary; only allowed before
148  // the first write. Returns false if the dictionary could not be attached.
149  pub fn attach_dictionary(&mut self, dict: <StandardAlloc as Allocator<u8>>::AllocatedMemory) -> bool {
150    self.0.attach_dictionary(dict)
151  }
152
153  // Attaches a serialized shared dictionary (magic 0x91 0x00, may contain an
154  // LZ77 prefix dictionary and custom word/transform lists); only allowed
155  // before the first write.
156  pub fn attach_serialized_dictionary(&mut self, dict: <StandardAlloc as Allocator<u8>>::AllocatedMemory) -> bool {
157    self.0.attach_serialized_dictionary(dict)
158  }
159
160  // Sets a decoder parameter (see BrotliState::set_parameter); only allowed
161  // before the first write.
162  pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
163    self.0.set_parameter(param, value)
164  }
165
166  // Sets the smallest ring buffer the decoder starts from (see
167  // BrotliState::set_initial_ring_buffer_size); only allowed before the first
168  // write.
169  pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
170    self.0.set_initial_ring_buffer_size(size)
171  }
172
173  pub fn get_ref(&self) -> &W {
174      self.0.get_ref()
175  }
176  pub fn get_mut(&mut self) -> &mut W {
177      self.0.get_mut()
178  }
179  pub fn into_inner(self) -> Result<W, W> {
180    self.0.into_inner()
181  }
182}
183
184
185#[cfg(all(feature="unsafe", feature="std"))]
186pub struct DecompressorWriter<W: Write>(DecompressorWriterCustomAlloc<W,
187                                                         <HeapAlloc<u8>
188                                                          as Allocator<u8>>::AllocatedMemory,
189                                                         HeapAlloc<u8>,
190                                                         HeapAlloc<u32>,
191                                                         HeapAlloc<HuffmanCode> >);
192
193
194#[cfg(all(feature="unsafe", feature="std"))]
195impl<W: Write> DecompressorWriter<W> {
196  pub fn new(w: W, buffer_size: usize) -> Self {
197    let dict = <HeapAlloc<u8> as Allocator<u8>>::AllocatedMemory::default();
198    Self::new_with_custom_dictionary(w, buffer_size, dict)
199  }
200  pub fn new_with_custom_dictionary(w: W, buffer_size: usize, dict: <HeapAlloc<u8> as Allocator<u8>>::AllocatedMemory) -> Self {
201    let mut alloc_u8 = HeapAlloc::<u8>::new(0);
202    let buffer = alloc_u8.alloc_cell(if buffer_size == 0 {4096} else {buffer_size});
203    let alloc_u32 = HeapAlloc::<u32>::new(0);
204    let alloc_hc = HeapAlloc::<HuffmanCode>::new(HuffmanCode{bits:2, value: 1});
205    DecompressorWriter::<W>(DecompressorWriterCustomAlloc::<W,
206                                                <HeapAlloc<u8>
207                                                 as Allocator<u8>>::AllocatedMemory,
208                                                HeapAlloc<u8>,
209                                                HeapAlloc<u32>,
210                                                HeapAlloc<HuffmanCode> >
211      ::new_with_custom_dictionary(w, buffer, alloc_u8, alloc_u32, alloc_hc, dict))
212  }
213
214  // Attaches an additional raw LZ77 prefix dictionary; only allowed before
215  // the first write. Returns false if the dictionary could not be attached.
216  pub fn attach_dictionary(&mut self, dict: <HeapAlloc<u8> as Allocator<u8>>::AllocatedMemory) -> bool {
217    self.0.attach_dictionary(dict)
218  }
219
220  // Attaches a serialized shared dictionary (magic 0x91 0x00, may contain an
221  // LZ77 prefix dictionary and custom word/transform lists); only allowed
222  // before the first write.
223  pub fn attach_serialized_dictionary(&mut self, dict: <HeapAlloc<u8> as Allocator<u8>>::AllocatedMemory) -> bool {
224    self.0.attach_serialized_dictionary(dict)
225  }
226
227  // Sets a decoder parameter (see BrotliState::set_parameter); only allowed
228  // before the first write.
229  pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
230    self.0.set_parameter(param, value)
231  }
232
233  // Sets the smallest ring buffer the decoder starts from (see
234  // BrotliState::set_initial_ring_buffer_size); only allowed before the first
235  // write.
236  pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
237    self.0.set_initial_ring_buffer_size(size)
238  }
239
240  pub fn get_ref(&self) -> &W {
241      self.0.get_ref()
242  }
243  pub fn get_mut(&mut self) -> &mut W {
244    &mut (self.0).0.get_mut().0
245  }
246  pub fn into_inner(self) -> Result<W, W> {
247    self.0.into_inner()
248  }
249}
250
251#[cfg(feature="std")]
252impl<W: Write> DecompressorWriter<W> {
253    pub fn close(&mut self) -> Result<(), Error>{
254        self.0.close()
255    }
256}
257#[cfg(feature="std")]
258impl<W: Write> Write for DecompressorWriter<W> {
259  	fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
260       self.0.write(buf)
261    }
262  	fn flush(&mut self) -> Result<(), Error> {
263       self.0.flush()
264    }
265}
266
267pub struct DecompressorWriterCustomIo<ErrType,
268                                W: CustomWrite<ErrType>,
269                                BufferType: SliceWrapperMut<u8>,
270                                AllocU8: Allocator<u8>,
271                                AllocU32: Allocator<u32>,
272                                AllocHC: Allocator<HuffmanCode>>
273{
274  output_buffer: BufferType,
275  total_out: usize,
276  output: Option<W>,
277  error_if_invalid_data: Option<ErrType>,
278  state: BrotliState<AllocU8, AllocU32, AllocHC>,
279}
280
281
282pub fn write_all<ErrType, W: CustomWrite<ErrType>>(writer: &mut W, mut buf : &[u8]) -> Result<(), ErrType> {
283    while buf.len() != 0 {
284          match writer.write(buf) {
285                Ok(bytes_written) => buf = &buf[bytes_written..],
286                Err(e) => return Err(e),
287          }
288    }
289    Ok(())
290}
291
292
293impl<ErrType,
294     W: CustomWrite<ErrType>,
295     BufferType : SliceWrapperMut<u8>,
296     AllocU8,
297     AllocU32,
298     AllocHC> DecompressorWriterCustomIo<ErrType, W, BufferType, AllocU8, AllocU32, AllocHC>
299 where AllocU8 : Allocator<u8>, AllocU32 : Allocator<u32>, AllocHC : Allocator<HuffmanCode>
300{
301
302    pub fn new(w: W, buffer : BufferType,
303               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC,
304               invalid_data_error_type : ErrType) -> Self {
305           let dict = AllocU8::AllocatedMemory::default();
306           Self::new_with_custom_dictionary(w, buffer, alloc_u8, alloc_u32, alloc_hc, dict, invalid_data_error_type)
307    }
308    pub fn new_with_custom_dictionary(w: W, buffer : BufferType,
309               alloc_u8 : AllocU8, alloc_u32 : AllocU32, alloc_hc : AllocHC,
310               dict: AllocU8::AllocatedMemory,
311               invalid_data_error_type : ErrType) -> Self {
312        DecompressorWriterCustomIo::<ErrType, W, BufferType, AllocU8, AllocU32, AllocHC>{
313            output_buffer : buffer,
314            total_out : 0,
315            output: Some(w),
316            state : BrotliState::new_with_custom_dictionary(alloc_u8,
317                                                                 alloc_u32,
318                                                                 alloc_hc,
319                                                                 dict),
320            error_if_invalid_data : Some(invalid_data_error_type),
321        }
322    }
323    pub fn close(&mut self) -> Result<(), ErrType>{
324        loop {
325            let mut avail_in : usize = 0;
326            let mut input_offset : usize = 0;
327            let mut avail_out : usize = self.output_buffer.slice_mut().len();
328            let mut output_offset : usize = 0;
329            let ret = BrotliDecompressStream(
330                &mut avail_in,
331                &mut input_offset,
332                &[],
333                &mut avail_out,
334                &mut output_offset,
335                self.output_buffer.slice_mut(),                
336                &mut self.total_out,
337                &mut self.state);
338          // already closed.
339          if self.error_if_invalid_data.is_none() {
340              return Ok(());
341          }
342          match write_all(self.output.as_mut().unwrap(), &self.output_buffer.slice_mut()[..output_offset]) {
343            Ok(_) => {},
344            Err(e) => return Err(e),
345           }
346           match ret {
347           BrotliResult::NeedsMoreInput => return self.error_if_invalid_data.take().map(|e|Err(e)).unwrap_or(Ok(())),
348           BrotliResult::NeedsMoreOutput => {},
349           BrotliResult::ResultSuccess => {
350               return Ok(());
351           },
352           BrotliResult::ResultFailure => return self.error_if_invalid_data.take().map(|e|Err(e)).unwrap_or(Ok(()))
353           }
354        }
355    }
356
357    // Attaches an additional raw LZ77 prefix dictionary; only allowed before
358    // the first write. Returns false if the dictionary could not be attached.
359    pub fn attach_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
360      self.state.attach_dictionary(dict)
361    }
362
363    // Attaches a serialized shared dictionary (magic 0x91 0x00, may contain
364    // an LZ77 prefix dictionary and custom word/transform lists); only
365    // allowed before the first write.
366    pub fn attach_serialized_dictionary(&mut self, dict: AllocU8::AllocatedMemory) -> bool {
367      self.state.attach_serialized_dictionary(dict)
368    }
369
370    // Sets a decoder parameter (see BrotliState::set_parameter); only
371    // allowed before the first write.
372    pub fn set_parameter(&mut self, param: BrotliDecoderParameter, value: u32) -> bool {
373      self.state.set_parameter(param, value)
374    }
375
376    // Sets the smallest ring buffer the decoder starts from (see
377    // BrotliState::set_initial_ring_buffer_size); only allowed before the
378    // first write.
379    pub fn set_initial_ring_buffer_size(&mut self, size: u32) -> bool {
380      self.state.set_initial_ring_buffer_size(size)
381    }
382
383    pub fn get_ref(&self) -> &W {
384        self.output.as_ref().unwrap()
385    }
386    pub fn get_mut(&mut self) -> &mut W {
387        self.output.as_mut().unwrap()
388    }
389    pub fn into_inner(mut self) -> Result<W, W> {
390        match self.close() {
391            Ok(_) => Ok((core::mem::replace(&mut self.output, None).unwrap())),
392            Err(_) => Err((core::mem::replace(&mut self.output, None).unwrap())),
393        }
394    }
395}
396
397impl<ErrType,
398     W: CustomWrite<ErrType>,
399     BufferType : SliceWrapperMut<u8>,
400     AllocU8 : Allocator<u8>,
401     AllocU32 : Allocator<u32>,
402     AllocHC : Allocator<HuffmanCode> > Drop for DecompressorWriterCustomIo<ErrType,
403                                                                                     W,
404                                                                                     BufferType,
405                                                                                     AllocU8,
406                                                                                     AllocU32,
407                                                                                     AllocHC> {
408    fn drop(&mut self) {
409        if self.output.is_some() {
410            match self.close() {
411                Ok(_) => {},
412                Err(_) => {},
413            }
414        }
415    }
416}
417
418impl<ErrType,
419     W: CustomWrite<ErrType>,
420     BufferType : SliceWrapperMut<u8>,
421     AllocU8 : Allocator<u8>,
422     AllocU32 : Allocator<u32>,
423     AllocHC : Allocator<HuffmanCode> > CustomWrite<ErrType> for DecompressorWriterCustomIo<ErrType,
424                                                                                     W,
425                                                                                     BufferType,
426                                                                                     AllocU8,
427                                                                                     AllocU32,
428                                                                                     AllocHC> {
429	fn write(&mut self, buf: &[u8]) -> Result<usize, ErrType > {
430        let mut avail_in = buf.len();
431        let mut input_offset : usize = 0;
432        loop {
433            let mut output_offset = 0;
434            let mut avail_out = self.output_buffer.slice_mut().len();
435            let op_result = BrotliDecompressStream(&mut avail_in,
436                                     &mut input_offset,
437                                     &buf[..],
438                                     &mut avail_out,
439                                     &mut output_offset,
440                                     self.output_buffer.slice_mut(),
441                                     &mut self.total_out,
442                                     &mut self.state);
443         match write_all(self.output.as_mut().unwrap(), &self.output_buffer.slice_mut()[..output_offset]) {
444          Ok(_) => {},
445          Err(e) => return Err(e),
446         }
447         match op_result {
448          BrotliResult::NeedsMoreInput => assert_eq!(avail_in, 0),
449          BrotliResult::NeedsMoreOutput => continue,
450          BrotliResult::ResultSuccess => {
451              return Ok(input_offset);
452          }
453          BrotliResult::ResultFailure => return self.error_if_invalid_data.take().map(|e|Err(e)).unwrap_or(Ok(0)),
454       }
455        if avail_in == 0 {
456           break
457        }
458      }
459      Ok(buf.len())
460    }
461    fn flush(&mut self) -> Result<(), ErrType> {
462       self.output.as_mut().unwrap().flush()
463    }
464}
465
466#[cfg(feature="std")]
467#[cfg(test)]
468mod test {
469    use super::DecompressorWriter;
470    use std::vec::Vec;
471    use std::io::Write;
472    // Brotli-compressed "hello\n" and 2 extra bytes
473
474
475    #[test]
476    fn write_extra() {
477        let contents = b"\x8f\x02\x80\x68\x65\x6c\x6c\x6f\x0a\x03\x67\x6f\x6f\x64\x62\x79\x65\x0a";
478        let mut decoder = DecompressorWriter::new(Vec::new(), 0);
479        let n = decoder.write(contents).unwrap();
480        assert_eq!(n, 10);
481        // Ensure that we can continue to not send data to the writer
482        // as it has consumed the entire file.
483        let n = decoder.write(contents).unwrap();
484        assert_eq!(n, 0);
485
486        let mut decoder = DecompressorWriter::new(Vec::new(), 0);
487        let e = decoder.write_all(contents).unwrap_err();
488        assert!(e.kind() == std::io::ErrorKind::WriteZero);
489        assert_eq!(decoder.get_ref().as_slice(), b"hello\n");
490    }
491}