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