| 1 |
use crate::encoder::compression::*; |
| 2 |
use flate2::{write::ZlibEncoder, Compression as FlateCompression}; |
| 3 |
|
| 4 |
/// The Deflate algorithm used to compress image data in TIFF files. |
| 5 |
#[derive(Debug, Clone, Copy)] |
| 6 |
pub struct Deflate { |
| 7 |
level: FlateCompression, |
| 8 |
} |
| 9 |
|
| 10 |
/// The level of compression used by the Deflate algorithm. |
| 11 |
/// It allows trading compression ratio for compression speed. |
| 12 |
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 13 |
#[non_exhaustive] |
| 14 |
#[derive(Default)] |
| 15 |
pub enum DeflateLevel { |
| 16 |
/// The fastest possible compression mode. |
| 17 |
Fast = 1, |
| 18 |
/// The conserative choice between speed and ratio. |
| 19 |
#[default] |
| 20 |
Balanced = 6, |
| 21 |
/// The best compression available with Deflate. |
| 22 |
Best = 9, |
| 23 |
} |
| 24 |
|
| 25 |
impl Deflate { |
| 26 |
/// Create a new deflate compressor with a specific level of compression. |
| 27 |
pub fn with_level(level: DeflateLevel) -> Self { |
| 28 |
Self { |
| 29 |
level: FlateCompression::new(level as u32), |
| 30 |
} |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
impl Default for Deflate { |
| 35 |
fn default() -> Self { |
| 36 |
Self::with_level(DeflateLevel::default()) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
impl Compression for Deflate { |
| 41 |
const COMPRESSION_METHOD: CompressionMethod = CompressionMethod::Deflate; |
| 42 |
|
| 43 |
fn get_algorithm(&self) -> Compressor { |
| 44 |
Compressor::Deflate(*self) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
impl CompressionAlgorithm for Deflate { |
| 49 |
fn write_to<W: Write>(&mut self, writer: &mut W, bytes: &[u8]) -> Result<u64, io::Error> { |
| 50 |
let mut encoder = ZlibEncoder::new(writer, self.level); |
| 51 |
encoder.write_all(bytes)?; |
| 52 |
encoder.try_finish()?; |
| 53 |
Ok(encoder.total_out()) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
#[cfg(test)] |
| 58 |
mod tests { |
| 59 |
use super::*; |
| 60 |
use crate::encoder::compression::tests::TEST_DATA; |
| 61 |
use std::io::Cursor; |
| 62 |
|
| 63 |
#[test] |
| 64 |
fn test_deflate() { |
| 65 |
const EXPECTED_COMPRESSED_DATA: [u8; 64] = [ |
| 66 |
0x78, 0x9C, 0x15, 0xC7, 0xD1, 0x0D, 0x80, 0x20, 0x0C, 0x04, 0xD0, 0x55, 0x6E, 0x02, |
| 67 |
0xA7, 0x71, 0x81, 0xA6, 0x41, 0xDA, 0x28, 0xD4, 0xF4, 0xD0, 0xF9, 0x81, 0xE4, 0xFD, |
| 68 |
0xBC, 0xD3, 0x9C, 0x58, 0x04, 0x1C, 0xE9, 0xBD, 0xE2, 0x8A, 0x84, 0x5A, 0xD1, 0x7B, |
| 69 |
0xE7, 0x97, 0xF4, 0xF8, 0x08, 0x8D, 0xF6, 0x66, 0x21, 0x3D, 0x3A, 0xE4, 0xA9, 0x91, |
| 70 |
0x3E, 0xAC, 0xF1, 0x98, 0xB9, 0x70, 0x17, 0x13, |
| 71 |
]; |
| 72 |
|
| 73 |
let mut compressed_data = Vec::<u8>::new(); |
| 74 |
let mut writer = Cursor::new(&mut compressed_data); |
| 75 |
Deflate::default().write_to(&mut writer, TEST_DATA).unwrap(); |
| 76 |
assert_eq!(EXPECTED_COMPRESSED_DATA, compressed_data.as_slice()); |
| 77 |
} |
| 78 |
} |