| 1 | use super::{BufReadCompressor, Dictionary, Preferences}; |
| 2 | use crate::lz4f::Result; |
| 3 | use std::{ |
| 4 | fmt, |
| 5 | io::{BufReader, Read}, |
| 6 | }; |
| 7 | |
| 8 | /// The [`Read`]-based streaming compressor. |
| 9 | /// |
| 10 | /// # Example |
| 11 | /// |
| 12 | /// ``` |
| 13 | /// # use std::env; |
| 14 | /// # use std::path::Path; |
| 15 | /// # use lzzzz::{Error, Result}; |
| 16 | /// # use assert_fs::prelude::*; |
| 17 | /// # let tmp_dir = assert_fs::TempDir::new().unwrap().into_persistent(); |
| 18 | /// # env::set_current_dir(tmp_dir.path()).unwrap(); |
| 19 | /// # |
| 20 | /// # tmp_dir.child("foo.txt").write_str("Hello").unwrap(); |
| 21 | /// # |
| 22 | /// use lzzzz::lz4f::ReadCompressor; |
| 23 | /// use std::{fs::File, io::prelude::*}; |
| 24 | /// |
| 25 | /// let mut f = File::open("foo.txt")?; |
| 26 | /// let mut r = ReadCompressor::new(&mut f, Default::default())?; |
| 27 | /// |
| 28 | /// let mut buf = Vec::new(); |
| 29 | /// r.read_to_end(&mut buf)?; |
| 30 | /// # Ok::<(), std::io::Error>(()) |
| 31 | /// ``` |
| 32 | /// |
| 33 | /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html |
| 34 | pub struct ReadCompressor<R: Read> { |
| 35 | inner: BufReadCompressor<BufReader<R>>, |
| 36 | } |
| 37 | |
| 38 | impl<R: Read> ReadCompressor<R> { |
| 39 | /// Creates a new `ReadCompressor<R>`. |
| 40 | pub fn new(reader: R, prefs: Preferences) -> Result<Self> { |
| 41 | Ok(Self { |
| 42 | inner: BufReadCompressor::new(BufReader::new(reader), prefs)?, |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | /// Creates a new `ReadCompressor<R>` with a dictionary. |
| 47 | pub fn with_dict(reader: R, prefs: Preferences, dict: Dictionary) -> Result<Self> { |
| 48 | Ok(Self { |
| 49 | inner: BufReadCompressor::with_dict(BufReader::new(reader), prefs, dict)?, |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | /// Returns ownership of the reader. |
| 54 | pub fn into_inner(self) -> R { |
| 55 | self.inner.into_inner().into_inner() |
| 56 | } |
| 57 | |
| 58 | /// Returns a mutable reference to the reader. |
| 59 | pub fn get_mut(&mut self) -> &mut R { |
| 60 | self.inner.get_mut().get_mut() |
| 61 | } |
| 62 | |
| 63 | /// Returns a shared reference to the reader. |
| 64 | pub fn get_ref(&self) -> &R { |
| 65 | self.inner.get_ref().get_ref() |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl<R> fmt::Debug for ReadCompressor<R> |
| 70 | where |
| 71 | R: Read + fmt::Debug, |
| 72 | { |
| 73 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 74 | fmt.debug_struct("ReadCompressor") |
| 75 | .field("reader", &self.inner.inner.get_ref()) |
| 76 | .field("prefs", &self.inner.comp.prefs()) |
| 77 | .finish() |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl<R: Read> Read for ReadCompressor<R> { |
| 82 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { |
| 83 | self.inner.read(buf) |
| 84 | } |
| 85 | } |