singlefile_formats/compression/
flate.rs

1#![cfg_attr(docsrs, doc(cfg(feature = "flate")))]
2#![cfg(feature = "flate")]
3
4//! Defines [`CompressionFormat`]s for the DEFLATE, gzip and zlib compression algorithms.
5
6pub extern crate flate2 as original;
7
8use crate::compression::{CompressionFormat, CompressionFormatLevels};
9
10use std::io::{Read, Write};
11
12/// A [`CompressionFormat`] corresponding to the DEFLATE compression algorithm.
13/// Implemented using the [`flate2`] crate.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub struct Deflate;
16
17impl CompressionFormat for Deflate {
18  type Encoder<W: Write> = flate2::write::DeflateEncoder::<W>;
19  type Decoder<R: Read> = flate2::read::DeflateDecoder::<R>;
20
21  fn encode_writer<W: Write>(&self, writer: W, compression: u32) -> Self::Encoder<W> {
22    Self::Encoder::new(writer, flate2::Compression::new(compression))
23  }
24
25  fn decode_reader<R: Read>(&self, reader: R) -> Self::Decoder<R> {
26    Self::Decoder::new(reader)
27  }
28}
29
30impl CompressionFormatLevels for Deflate {
31  const COMPRESSION_LEVEL_NONE: u32 = 0;
32  const COMPRESSION_LEVEL_FAST: u32 = 1;
33  const COMPRESSION_LEVEL_BEST: u32 = 9;
34  const COMPRESSION_LEVEL_DEFAULT: u32 = 6;
35}
36
37/// A [`CompressionFormat`] corresponding to the gzip compression algorithm.
38/// Implemented using the [`flate2`] crate.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub struct Gz;
41
42impl CompressionFormat for Gz {
43  type Encoder<W: Write> = flate2::write::GzEncoder::<W>;
44  type Decoder<R: Read> = flate2::read::GzDecoder::<R>;
45
46  fn encode_writer<W: Write>(&self, writer: W, compression: u32) -> Self::Encoder<W> {
47    Self::Encoder::new(writer, flate2::Compression::new(compression))
48  }
49
50  fn decode_reader<R: Read>(&self, reader: R) -> Self::Decoder<R> {
51    Self::Decoder::new(reader)
52  }
53}
54
55impl CompressionFormatLevels for Gz {
56  const COMPRESSION_LEVEL_NONE: u32 = 0;
57  const COMPRESSION_LEVEL_FAST: u32 = 1;
58  const COMPRESSION_LEVEL_BEST: u32 = 9;
59  const COMPRESSION_LEVEL_DEFAULT: u32 = 6;
60}
61
62/// A [`CompressionFormat`] corresponding to the zlib compression algorithm.
63/// Implemented using the [`flate2`] crate.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65pub struct ZLib;
66
67impl CompressionFormat for ZLib {
68  type Encoder<W: Write> = flate2::write::ZlibEncoder::<W>;
69  type Decoder<R: Read> = flate2::read::ZlibDecoder::<R>;
70
71  fn encode_writer<W: Write>(&self, writer: W, compression: u32) -> Self::Encoder<W> {
72    Self::Encoder::new(writer, flate2::Compression::new(compression))
73  }
74
75  fn decode_reader<R: Read>(&self, reader: R) -> Self::Decoder<R> {
76    Self::Decoder::new(reader)
77  }
78}
79
80impl CompressionFormatLevels for ZLib {
81  const COMPRESSION_LEVEL_NONE: u32 = 0;
82  const COMPRESSION_LEVEL_FAST: u32 = 1;
83  const COMPRESSION_LEVEL_BEST: u32 = 9;
84  const COMPRESSION_LEVEL_DEFAULT: u32 = 6;
85}