1use std::io::{self, Read, Write};
13
14use crate::ffi;
15use crate::{Algorithm, Error, Status};
16
17const SCRATCH: usize = 64 * 1024;
21
22impl From<Error> for io::Error {
23 fn from(e: Error) -> io::Error {
24 io::Error::new(io::ErrorKind::Other, e)
25 }
26}
27
28fn stuck_error() -> io::Error {
33 Error {
34 code: Status::Decompression,
35 message: "compress-utils: decoder made no progress (malformed or truncated input)"
36 .to_string(),
37 }
38 .into()
39}
40
41pub(crate) fn io_to_error(e: io::Error) -> Error {
44 let fallback = e.to_string();
45 match e.into_inner() {
46 Some(b) => match b.downcast::<Error>() {
47 Ok(err) => *err,
48 Err(b) => Error {
49 code: Status::Internal,
50 message: b.to_string(),
51 },
52 },
53 None => Error {
54 code: Status::Internal,
55 message: fallback,
56 },
57 }
58}
59
60pub struct Compressor<W: Write> {
67 sink: Option<W>,
68 stream: *mut ffi::cu_compress_stream,
69 scratch: Vec<u8>,
70 finished: bool,
71}
72
73impl<W: Write> Compressor<W> {
74 pub fn new(sink: W, algo: Algorithm, level: i32) -> Result<Self, Error> {
77 let mut stream: *mut ffi::cu_compress_stream = std::ptr::null_mut();
78 let st = unsafe { ffi::cu_compress_stream_create(algo.to_raw(), level, &mut stream) };
81 crate::check_status(st)?;
82 Ok(Compressor {
83 sink: Some(sink),
84 stream,
85 scratch: vec![0u8; SCRATCH],
86 finished: false,
87 })
88 }
89
90 pub fn finish(mut self) -> io::Result<W> {
92 self.do_finish()?;
93 self.destroy();
94 Ok(self.sink.take().expect("sink present"))
96 }
97
98 fn do_finish(&mut self) -> io::Result<()> {
100 if self.finished {
101 return Ok(());
102 }
103 loop {
104 let mut out_len = self.scratch.len();
105 let st = unsafe {
107 ffi::cu_compress_stream_finish(self.stream, self.scratch.as_mut_ptr(), &mut out_len)
108 };
109 if out_len > 0 {
110 self.sink
111 .as_mut()
112 .expect("sink present")
113 .write_all(&self.scratch[..out_len])?;
114 }
115 if st == ffi::CU_OK {
116 self.finished = true;
117 return Ok(());
118 }
119 if st != ffi::CU_ERR_BUF_TOO_SMALL {
120 return Err(crate::make_error(st).into());
121 }
122 if out_len == 0 {
123 return Err(stuck_error());
124 }
125 }
126 }
127
128 fn destroy(&mut self) {
129 if !self.stream.is_null() {
130 unsafe { ffi::cu_compress_stream_destroy(self.stream) };
132 self.stream = std::ptr::null_mut();
133 }
134 }
135}
136
137impl<W: Write> Write for Compressor<W> {
138 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
139 if self.finished {
140 return Err(io::Error::new(
141 io::ErrorKind::Other,
142 "compress-utils: stream is finished",
143 ));
144 }
145 if buf.is_empty() {
146 return Ok(0);
147 }
148 let sink = self.sink.as_mut().expect("sink present");
149 let mut first = true;
150 loop {
151 let mut out_len = self.scratch.len();
152 let (in_ptr, in_len) = if first {
155 (buf.as_ptr(), buf.len())
156 } else {
157 (std::ptr::null(), 0usize)
158 };
159 first = false;
160 let st = unsafe {
162 ffi::cu_compress_stream_write(
163 self.stream,
164 in_ptr,
165 in_len,
166 self.scratch.as_mut_ptr(),
167 &mut out_len,
168 )
169 };
170 if out_len > 0 {
171 sink.write_all(&self.scratch[..out_len])?;
172 }
173 if st == ffi::CU_OK {
174 return Ok(buf.len());
175 }
176 if st != ffi::CU_ERR_BUF_TOO_SMALL {
177 return Err(crate::make_error(st).into());
178 }
179 if out_len == 0 {
180 return Err(stuck_error());
181 }
182 }
183 }
184
185 fn flush(&mut self) -> io::Result<()> {
186 if let Some(sink) = self.sink.as_mut() {
190 sink.flush()
191 } else {
192 Ok(())
193 }
194 }
195}
196
197impl<W: Write> Drop for Compressor<W> {
198 fn drop(&mut self) {
199 if self.sink.is_some() && !self.finished {
202 let _ = self.do_finish();
203 }
204 self.destroy();
205 }
206}
207
208pub struct Decompressor<R: Read> {
210 src: R,
211 stream: *mut ffi::cu_decompress_stream,
212 in_buf: Vec<u8>,
213 scratch: Vec<u8>,
214 out: Vec<u8>,
215 out_pos: usize,
216
217 input_done: bool,
218 draining: bool,
219 finished: bool,
220}
221
222impl<R: Read> Decompressor<R> {
223 pub fn new(src: R, algo: Algorithm) -> Result<Self, Error> {
225 let mut stream: *mut ffi::cu_decompress_stream = std::ptr::null_mut();
226 let st = unsafe { ffi::cu_decompress_stream_create(algo.to_raw(), &mut stream) };
228 crate::check_status(st)?;
229 Ok(Decompressor {
230 src,
231 stream,
232 in_buf: vec![0u8; SCRATCH],
233 scratch: vec![0u8; SCRATCH],
234 out: Vec::new(),
235 out_pos: 0,
236 input_done: false,
237 draining: false,
238 finished: false,
239 })
240 }
241
242 fn pump(&mut self) -> io::Result<()> {
245 if self.input_done && !self.draining {
247 let mut out_len = self.scratch.len();
248 let st = unsafe {
250 ffi::cu_decompress_stream_finish(
251 self.stream,
252 self.scratch.as_mut_ptr(),
253 &mut out_len,
254 )
255 };
256 if out_len > 0 {
257 self.out.extend_from_slice(&self.scratch[..out_len]);
258 }
259 if st == ffi::CU_OK {
260 self.finished = true;
261 return Ok(());
262 }
263 if st == ffi::CU_ERR_BUF_TOO_SMALL {
264 if out_len == 0 {
265 return Err(stuck_error());
266 }
267 return Ok(()); }
269 return Err(crate::make_error(st).into());
270 }
271
272 let mut fed = 0usize;
275 if !self.draining {
276 let n = self.src.read(&mut self.in_buf)?;
277 if n == 0 {
278 self.input_done = true;
279 return Ok(()); }
281 fed = n;
282 }
283
284 let mut out_len = self.scratch.len();
285 let (in_ptr, in_len) = if self.draining {
286 (std::ptr::null(), 0usize)
287 } else {
288 (self.in_buf.as_ptr(), fed)
289 };
290 let st = unsafe {
292 ffi::cu_decompress_stream_write(
293 self.stream,
294 in_ptr,
295 in_len,
296 self.scratch.as_mut_ptr(),
297 &mut out_len,
298 )
299 };
300 if out_len > 0 {
301 self.out.extend_from_slice(&self.scratch[..out_len]);
302 }
303 match st {
304 ffi::CU_OK => {
305 self.draining = false;
306 Ok(())
307 }
308 ffi::CU_ERR_BUF_TOO_SMALL => {
309 if out_len == 0 {
310 return Err(stuck_error());
311 }
312 self.draining = true; Ok(())
314 }
315 other => Err(crate::make_error(other).into()),
316 }
317 }
318}
319
320impl<R: Read> Read for Decompressor<R> {
321 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
322 while self.out_pos == self.out.len() {
323 if self.finished {
324 return Ok(0);
325 }
326 self.out.clear();
328 self.out_pos = 0;
329 self.pump()?;
330 }
331 let n = std::cmp::min(buf.len(), self.out.len() - self.out_pos);
332 buf[..n].copy_from_slice(&self.out[self.out_pos..self.out_pos + n]);
333 self.out_pos += n;
334 Ok(n)
335 }
336}
337
338impl<R: Read> Drop for Decompressor<R> {
339 fn drop(&mut self) {
340 if !self.stream.is_null() {
341 unsafe { ffi::cu_decompress_stream_destroy(self.stream) };
343 self.stream = std::ptr::null_mut();
344 }
345 }
346}