1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use super::{Compressor, Dictionary, Preferences};
use crate::lz4f::Result;
use std::{fmt, io::Write};
pub struct WriteCompressor<W: Write> {
inner: Option<W>,
comp: Compressor,
}
impl<W: Write> WriteCompressor<W> {
pub fn new(writer: W, prefs: Preferences) -> Result<Self> {
Ok(Self {
inner: Some(writer),
comp: Compressor::new(prefs, None)?,
})
}
pub fn with_dict(writer: W, prefs: Preferences, dict: Dictionary) -> Result<Self> {
Ok(Self {
inner: Some(writer),
comp: Compressor::new(prefs, Some(dict))?,
})
}
pub fn get_mut(&mut self) -> &mut W {
self.inner.as_mut().unwrap()
}
pub fn get_ref(&self) -> &W {
self.inner.as_ref().unwrap()
}
pub fn into_inner(mut self) -> W {
let _ = self.end();
self.inner.take().unwrap()
}
fn end(&mut self) -> std::io::Result<()> {
if let Some(device) = &mut self.inner {
self.comp.end(false)?;
device.write_all(self.comp.buf())?;
self.comp.clear_buf();
device.flush()?;
}
Ok(())
}
}
impl<W> fmt::Debug for WriteCompressor<W>
where
W: Write + fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("WriteCompressor")
.field("writer", &self.inner)
.field("prefs", &self.comp.prefs())
.finish()
}
}
impl<W: Write> Write for WriteCompressor<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.comp.update(buf, false)?;
self.inner.as_mut().unwrap().write_all(self.comp.buf())?;
self.comp.clear_buf();
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.comp.flush(false)?;
self.inner.as_mut().unwrap().write_all(self.comp.buf())?;
self.comp.clear_buf();
self.inner.as_mut().unwrap().flush()
}
}
impl<W: Write> Drop for WriteCompressor<W> {
fn drop(&mut self) {
let _ = self.end();
}
}