Debian Codegraph @

src/lz4f/stream/decomp/write.rs

raw symbols SCIP
1 use crate::lz4f::{Decompressor, FrameInfo, Result};
2 use std::{borrow::Cow, fmt, io::Write};
3
4 /// The [`Write`]-based streaming decompressor.
5 ///
6 /// # Example
7 ///
8 /// ```
9 /// # use std::env;
10 /// # use std::path::Path;
11 /// # use lzzzz::{Error, Result};
12 /// # use assert_fs::prelude::*;
13 /// # let tmp_dir = assert_fs::TempDir::new().unwrap().into_persistent();
14 /// # env::set_current_dir(tmp_dir.path()).unwrap();
15 /// use lzzzz::lz4f::{compress_to_vec, WriteDecompressor};
16 /// use std::{fs::File, io::prelude::*};
17 ///
18 /// let mut f = File::create("foo.txt")?;
19 /// let mut w = WriteDecompressor::new(&mut f)?;
20 ///
21 /// let mut buf = Vec::new();
22 /// compress_to_vec(b"Hello world!", &mut buf, &Default::default())?;
23 ///
24 /// w.write_all(&buf)?;
25 /// # Ok::<(), std::io::Error>(())
26 /// ```
27 ///
28 /// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
29 pub struct WriteDecompressor<'a, W: Write> {
30 inner: W,
31 decomp: Decompressor<'a>,
32 }
33
34 impl<'a, W: Write> WriteDecompressor<'a, W> {
35 /// Creates a new `WriteDecompressor<W>`.
36 pub fn new(writer: W) -> Result<Self> {
37 Ok(Self {
38 inner: writer,
39 decomp: Decompressor::new()?,
40 })
41 }
42
43 /// Sets the dictionary.
44 pub fn set_dict<D>(&mut self, dict: D)
45 where
46 D: Into<Cow<'a, [u8]>>,
47 {
48 self.decomp.set_dict(dict);
49 }
50
51 /// Returns `FrameInfo` if the frame header is already decoded.
52 /// Otherwise, returns `None`.
53 pub fn frame_info(&self) -> Option<FrameInfo> {
54 self.decomp.frame_info()
55 }
56
57 /// Sets the 'header-only' mode.
58 ///
59 /// When the 'header-only' mode is enabled, the decompressor doesn't
60 /// consume the frame body and `write()` always returns `Ok(0)`
61 /// if the frame header is already decoded.
62 pub fn decode_header_only(&mut self, flag: bool) {
63 self.decomp.decode_header_only(flag);
64 }
65
66 /// Returns a mutable reference to the writer.
67 pub fn get_mut(&mut self) -> &mut W {
68 &mut self.inner
69 }
70
71 /// Returns a shared reference to the writer.
72 pub fn get_ref(&self) -> &W {
73 &self.inner
74 }
75
76 /// Returns ownership of the writer.
77 pub fn into_inner(self) -> W {
78 self.inner
79 }
80 }
81
82 impl<W> fmt::Debug for WriteDecompressor<'_, W>
83 where
84 W: Write + fmt::Debug,
85 {
86 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
87 fmt.debug_struct("WriteDecompressor")
88 .field("writer", &self.inner)
89 .finish()
90 }
91 }
92
93 impl<W: Write> Write for WriteDecompressor<'_, W> {
94 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
95 let report = self.decomp.decompress(buf)?;
96 self.inner.write_all(self.decomp.buf())?;
97 self.decomp.clear_buf();
98 Ok(report)
99 }
100
101 fn flush(&mut self) -> std::io::Result<()> {
102 self.inner.flush()
103 }
104 }