| 1 | //! Various compression formats support. |
| 2 | #[cfg(feature="deflate")] |
| 3 | #[allow(clippy::manual_range_contains)] |
| 4 | pub mod deflate; |
| 5 | |
| 6 | use crate::io::byteio::ByteIOError; |
| 7 | use crate::io::bitreader::BitReaderError; |
| 8 | use crate::io::codebook::CodebookError; |
| 9 | |
| 10 | /// A list specifying general compression errors. |
| 11 | #[derive(Debug)] |
| 12 | pub enum DecompressError { |
| 13 | /// Compressed stream header contains errors. |
| 14 | InvalidHeader, |
| 15 | /// Compressed stream checksum does not match unpacked contents. |
| 16 | CRCError, |
| 17 | /// Compressed stream contains a combination of bits that cannot be decoded. |
| 18 | InvalidData, |
| 19 | /// Compressed stream ended prematurely. |
| 20 | ShortData, |
| 21 | /// There is more data than what can fit output buffer. |
| 22 | OutputFull, |
| 23 | /// Provided function argument is invalid. |
| 24 | InvalidArgument, |
| 25 | /// Compressed stream contains features that cannot be decoded. |
| 26 | Unsupported, |
| 27 | /// Underlying input reader had a problem. |
| 28 | IOError, |
| 29 | } |
| 30 | |
| 31 | /// A specialised `Result` type for codebook operations. |
| 32 | pub type DecompressResult<T> = Result<T, DecompressError>; |
| 33 | |
| 34 | impl From<ByteIOError> for DecompressError { |
| 35 | fn from(e: ByteIOError) -> Self { |
| 36 | match e { |
| 37 | ByteIOError::EOF => DecompressError::ShortData, |
| 38 | _ => DecompressError::IOError, |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | impl From<BitReaderError> for DecompressError { |
| 44 | fn from(e: BitReaderError) -> Self { |
| 45 | match e { |
| 46 | BitReaderError::BitstreamEnd => DecompressError::ShortData, |
| 47 | _ => DecompressError::InvalidData, |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | impl From<CodebookError> for DecompressError { |
| 53 | fn from(_: CodebookError) -> Self { |
| 54 | DecompressError::InvalidData |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | ///! Copies requested amount of bytes from previous position in the same buffer. |
| 59 | ///! If source area overlaps with destination area already copied values should be used e.g. copying with offset 1 means essentially to repeat previous byte requested number of times. |
| 60 | pub fn lz_copy(buf: &mut [u8], dst_pos: usize, offset: usize, len: usize) { |
| 61 | if dst_pos < offset { |
| 62 | panic!("Copy offset is before buffer start."); |
| 63 | } |
| 64 | let ipos = dst_pos - offset; |
| 65 | let buf = &mut buf[ipos..]; |
| 66 | if ipos + len <= dst_pos { |
| 67 | let (src, dst) = buf.split_at_mut(offset); |
| 68 | dst[..len].copy_from_slice(&src[..len]); |
| 69 | } else { |
| 70 | for i in 0..len { |
| 71 | buf[offset + i] = buf[i]; |
| 72 | } |
| 73 | } |
| 74 | } |