1 use std::io; 2 use std::io::prelude::*; 3 4 #[cfg(feature = "tokio")] 5 use futures::Poll; 6 #[cfg(feature = "tokio")] 7 use tokio_io::{AsyncRead, AsyncWrite}; 8 9 use super::bufread; 10 use crate::bufreader::BufReader; 11 12 /// A DEFLATE encoder, or compressor. 13 /// 14 /// This structure implements a [`Read`] interface and will read uncompressed 15 /// data from an underlying stream and emit a stream of compressed data. 16 /// 17 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html 18 /// 19 /// # Examples 20 /// 21 /// ``` 22 /// use std::io::prelude::*; 23 /// use std::io; 24 /// use flate2::Compression; 25 /// use flate2::read::DeflateEncoder; 26 /// 27 /// # fn main() { 28 /// # println!("{:?}", deflateencoder_read_hello_world().unwrap()); 29 /// # } 30 /// # 31 /// // Return a vector containing the Deflate compressed version of hello world 32 /// fn deflateencoder_read_hello_world() -> io::Result<Vec<u8>> { 33 /// let mut ret_vec = [0;100]; 34 /// let c = b"hello world"; 35 /// let mut deflater = DeflateEncoder::new(&c[..], Compression::fast()); 36 /// let count = deflater.read(&mut ret_vec)?; 37 /// Ok(ret_vec[0..count].to_vec()) 38 /// } 39 /// ``` 40 #[derive(Debug)] 41 pub struct DeflateEncoder<R> { 42 inner: bufread::DeflateEncoder<BufReader<R>>, 43 } 44 45 impl<R: Read> DeflateEncoder<R> { 46 /// Creates a new encoder which will read uncompressed data from the given 47 /// stream and emit the compressed stream. new(r: R, level: crate::Compression) -> DeflateEncoder<R>48 pub fn new(r: R, level: crate::Compression) -> DeflateEncoder<R> { 49 DeflateEncoder { 50 inner: bufread::DeflateEncoder::new(BufReader::new(r), level), 51 } 52 } 53 } 54 55 impl<R> DeflateEncoder<R> { 56 /// Resets the state of this encoder entirely, swapping out the input 57 /// stream for another. 58 /// 59 /// This function will reset the internal state of this encoder and replace 60 /// the input stream with the one provided, returning the previous input 61 /// stream. Future data read from this encoder will be the compressed 62 /// version of `r`'s data. 63 /// 64 /// Note that there may be currently buffered data when this function is 65 /// called, and in that case the buffered data is discarded. reset(&mut self, r: R) -> R66 pub fn reset(&mut self, r: R) -> R { 67 super::bufread::reset_encoder_data(&mut self.inner); 68 self.inner.get_mut().reset(r) 69 } 70 71 /// Acquires a reference to the underlying reader get_ref(&self) -> &R72 pub fn get_ref(&self) -> &R { 73 self.inner.get_ref().get_ref() 74 } 75 76 /// Acquires a mutable reference to the underlying stream 77 /// 78 /// Note that mutation of the stream may result in surprising results if 79 /// this encoder is continued to be used. get_mut(&mut self) -> &mut R80 pub fn get_mut(&mut self) -> &mut R { 81 self.inner.get_mut().get_mut() 82 } 83 84 /// Consumes this encoder, returning the underlying reader. 85 /// 86 /// Note that there may be buffered bytes which are not re-acquired as part 87 /// of this transition. It's recommended to only call this function after 88 /// EOF has been reached. into_inner(self) -> R89 pub fn into_inner(self) -> R { 90 self.inner.into_inner().into_inner() 91 } 92 93 /// Returns the number of bytes that have been read into this compressor. 94 /// 95 /// Note that not all bytes read from the underlying object may be accounted 96 /// for, there may still be some active buffering. total_in(&self) -> u6497 pub fn total_in(&self) -> u64 { 98 self.inner.total_in() 99 } 100 101 /// Returns the number of bytes that the compressor has produced. 102 /// 103 /// Note that not all bytes may have been read yet, some may still be 104 /// buffered. total_out(&self) -> u64105 pub fn total_out(&self) -> u64 { 106 self.inner.total_out() 107 } 108 } 109 110 impl<R: Read> Read for DeflateEncoder<R> { read(&mut self, buf: &mut [u8]) -> io::Result<usize>111 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { 112 self.inner.read(buf) 113 } 114 } 115 116 #[cfg(feature = "tokio")] 117 impl<R: AsyncRead> AsyncRead for DeflateEncoder<R> {} 118 119 impl<W: Read + Write> Write for DeflateEncoder<W> { write(&mut self, buf: &[u8]) -> io::Result<usize>120 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 121 self.get_mut().write(buf) 122 } 123 flush(&mut self) -> io::Result<()>124 fn flush(&mut self) -> io::Result<()> { 125 self.get_mut().flush() 126 } 127 } 128 129 #[cfg(feature = "tokio")] 130 impl<R: AsyncRead + AsyncWrite> AsyncWrite for DeflateEncoder<R> { shutdown(&mut self) -> Poll<(), io::Error>131 fn shutdown(&mut self) -> Poll<(), io::Error> { 132 self.get_mut().shutdown() 133 } 134 } 135 136 /// A DEFLATE decoder, or decompressor. 137 /// 138 /// This structure implements a [`Read`] interface and takes a stream of 139 /// compressed data as input, providing the decompressed data when read from. 140 /// 141 /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html 142 /// 143 /// # Examples 144 /// 145 /// ``` 146 /// use std::io::prelude::*; 147 /// use std::io; 148 /// # use flate2::Compression; 149 /// # use flate2::write::DeflateEncoder; 150 /// use flate2::read::DeflateDecoder; 151 /// 152 /// # fn main() { 153 /// # let mut e = DeflateEncoder::new(Vec::new(), Compression::default()); 154 /// # e.write_all(b"Hello World").unwrap(); 155 /// # let bytes = e.finish().unwrap(); 156 /// # println!("{}", decode_reader(bytes).unwrap()); 157 /// # } 158 /// // Uncompresses a Deflate Encoded vector of bytes and returns a string or error 159 /// // Here &[u8] implements Read 160 /// fn decode_reader(bytes: Vec<u8>) -> io::Result<String> { 161 /// let mut deflater = DeflateDecoder::new(&bytes[..]); 162 /// let mut s = String::new(); 163 /// deflater.read_to_string(&mut s)?; 164 /// Ok(s) 165 /// } 166 /// ``` 167 #[derive(Debug)] 168 pub struct DeflateDecoder<R> { 169 inner: bufread::DeflateDecoder<BufReader<R>>, 170 } 171 172 impl<R: Read> DeflateDecoder<R> { 173 /// Creates a new decoder which will decompress data read from the given 174 /// stream. new(r: R) -> DeflateDecoder<R>175 pub fn new(r: R) -> DeflateDecoder<R> { 176 DeflateDecoder::new_with_buf(r, vec![0; 32 * 1024]) 177 } 178 179 /// Same as `new`, but the intermediate buffer for data is specified. 180 /// 181 /// Note that the capacity of the intermediate buffer is never increased, 182 /// and it is recommended for it to be large. new_with_buf(r: R, buf: Vec<u8>) -> DeflateDecoder<R>183 pub fn new_with_buf(r: R, buf: Vec<u8>) -> DeflateDecoder<R> { 184 DeflateDecoder { 185 inner: bufread::DeflateDecoder::new(BufReader::with_buf(buf, r)), 186 } 187 } 188 } 189 190 impl<R> DeflateDecoder<R> { 191 /// Resets the state of this decoder entirely, swapping out the input 192 /// stream for another. 193 /// 194 /// This will reset the internal state of this decoder and replace the 195 /// input stream with the one provided, returning the previous input 196 /// stream. Future data read from this decoder will be the decompressed 197 /// version of `r`'s data. 198 /// 199 /// Note that there may be currently buffered data when this function is 200 /// called, and in that case the buffered data is discarded. reset(&mut self, r: R) -> R201 pub fn reset(&mut self, r: R) -> R { 202 super::bufread::reset_decoder_data(&mut self.inner); 203 self.inner.get_mut().reset(r) 204 } 205 206 /// Acquires a reference to the underlying stream get_ref(&self) -> &R207 pub fn get_ref(&self) -> &R { 208 self.inner.get_ref().get_ref() 209 } 210 211 /// Acquires a mutable reference to the underlying stream 212 /// 213 /// Note that mutation of the stream may result in surprising results if 214 /// this encoder is continued to be used. get_mut(&mut self) -> &mut R215 pub fn get_mut(&mut self) -> &mut R { 216 self.inner.get_mut().get_mut() 217 } 218 219 /// Consumes this decoder, returning the underlying reader. 220 /// 221 /// Note that there may be buffered bytes which are not re-acquired as part 222 /// of this transition. It's recommended to only call this function after 223 /// EOF has been reached. into_inner(self) -> R224 pub fn into_inner(self) -> R { 225 self.inner.into_inner().into_inner() 226 } 227 228 /// Returns the number of bytes that the decompressor has consumed. 229 /// 230 /// Note that this will likely be smaller than what the decompressor 231 /// actually read from the underlying stream due to buffering. total_in(&self) -> u64232 pub fn total_in(&self) -> u64 { 233 self.inner.total_in() 234 } 235 236 /// Returns the number of bytes that the decompressor has produced. total_out(&self) -> u64237 pub fn total_out(&self) -> u64 { 238 self.inner.total_out() 239 } 240 } 241 242 impl<R: Read> Read for DeflateDecoder<R> { read(&mut self, into: &mut [u8]) -> io::Result<usize>243 fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { 244 self.inner.read(into) 245 } 246 } 247 248 #[cfg(feature = "tokio")] 249 impl<R: AsyncRead> AsyncRead for DeflateDecoder<R> {} 250 251 impl<W: Read + Write> Write for DeflateDecoder<W> { write(&mut self, buf: &[u8]) -> io::Result<usize>252 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 253 self.get_mut().write(buf) 254 } 255 flush(&mut self) -> io::Result<()>256 fn flush(&mut self) -> io::Result<()> { 257 self.get_mut().flush() 258 } 259 } 260 261 #[cfg(feature = "tokio")] 262 impl<R: AsyncWrite + AsyncRead> AsyncWrite for DeflateDecoder<R> { shutdown(&mut self) -> Poll<(), io::Error>263 fn shutdown(&mut self) -> Poll<(), io::Error> { 264 self.get_mut().shutdown() 265 } 266 } 267