aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordrfrugal <drfrugal@karazhan>2025-03-07 21:15:18 +0100
committerdrfrugal <drfrugal@karazhan>2025-03-07 21:15:18 +0100
commit0d054955d48711279e152e123a5aa75cbb49b60c (patch)
tree4d7e4657bfefabf615c3e80da17dccf4bcb67a0c
init
-rw-r--r--.gitignore2
-rw-r--r--Cargo.lock258
-rw-r--r--Cargo.toml3
-rw-r--r--LICENSE9
-rw-r--r--README.md62
-rw-r--r--cli/Cargo.toml8
-rw-r--r--cli/src/main.rs112
-rw-r--r--lib/Cargo.toml7
-rw-r--r--lib/src/lib.rs282
-rw-r--r--lib/tests/tests.rs59
10 files changed, 802 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4381362
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+/target
+/.idea
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..fcccb58
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,258 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anstream"
+version = "0.6.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9"
+
+[[package]]
+name = "anstyle-parse"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e"
+dependencies = [
+ "anstyle",
+ "once_cell",
+ "windows-sys",
+]
+
+[[package]]
+name = "clap"
+version = "4.5.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "027bb0d98429ae334a8698531da7077bdf906419543a35a55c2cb1b66437d767"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.5.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5589e0cba072e0f3d23791efac0fd8627b49c829c196a492e88168e6a669d863"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.5.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf4ced95c6f4a675af3da73304b9ac4ed991640c36374e4b46795c49e17cf1ed"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
+
+[[package]]
+name = "once_cell"
+version = "1.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.94"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1f1914ce909e1658d9907913b4b91947430c7d9be598b15a1912935b8c04801"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "syn"
+version = "2.0.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e02e925281e18ffd9d640e234264753c43edc62d64b2d4cf898f1bc5e75f3fc2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "zlib-header"
+version = "0.1.0"
+dependencies = [
+ "hex",
+]
+
+[[package]]
+name = "zlib-header-cli"
+version = "0.1.0"
+dependencies = [
+ "clap",
+ "zlib-header",
+]
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..22571be
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,3 @@
+[workspace]
+members = ["cli", "lib"]
+resolver = "2"
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..6934789
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2025 DrFrugal
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..651b6e8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,62 @@
+# zlib-header
+Rust binary and library to work with the 2 Byte zlib header, as defined in
+[RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950).
+This was initially written to reverse-engineer more details about Blizzard's proprietary MPQ archive format, which uses
+zlib streams to store data.
+## Binary
+```
+Usage: zlib-header-cli [OPTIONS] [HEX4CHAR]
+
+Arguments:
+[HEX4CHAR] A four-character hex string representing the ZlibHeader (Big Endian)
+
+Options:
+ -e, --explain Explain the ZlibHeader struct and abbreviations
+ -h, --help Print help
+```
+```
+drfrugal@karazhan:~$ zlib-header-cli 789C
+CM 8 (DEFLATE)
+CINFO 7 (Window: 32768 Bytes)
+FCHECK 28 (valid)
+FDICT false (Preset Dictionary not used)
+FLEVEL 2 (default)
+```
+```
+drfrugal@karazhan:~$ zlib-header-cli --explain
+2 Byte zlib header according to https://datatracker.ietf.org/doc/html/rfc1950
+1st Byte - CMF (Compression Method and Flags)
+ 0000_1111 CM Compression Method 8, _ (DEFLATE, UNDEFINED)
+ 1111_0000 CINFO Compression Info window size is 2.pow(CINFO + 8)
+2nd Byte - FLG (Flags)
+ 0001_1111 FCHECK Checksum Adjustment valid if (CMF * 256 + FLG) % 31 == 0
+ 0010_0000 FDICT Preset Dictionary a preset dictionary was used
+ 1100_0000 FLEVEL Compression Level 0, 1, 2, 3 (fastest, fast, default, best)
+```
+## Library
+Read the complete documentation [here](https://git.drfrugal.xyz/doc/zlib_header/).
+```
+use zlib_header::ZlibHeader;
+let cm = 8;
+let cinfo = 7;
+let fdict = false;
+let flevel = 2;
+let header = ZlibHeader::new(cm, cinfo, fdict, flevel);
+match header {
+ Ok(header) => {
+ println!("header is valid (strict): {}", header.is_valid_strict()); // header is valid (strict): true
+ },
+ Err(err) => eprintln!("Unable to initialize zlib header: {:?}", err)
+}
+```
+```
+use zlib_header::ZlibHeader;
+let header = ZlibHeader::default();
+println!("Display: {}", header); // Display: 789C
+println!("Debug: {:?}", header); // Debug: ZlibHeader { DEFLATE | 32768 Bytes | default | Dictionary: false | valid }
+let bytes = [0x78, 0x9C];
+println!("header matches expected bytes: {}", header == bytes); // header matches expected bytes: true
+```
+## Downloads
+[linux/x86_64/zlib-header-cli](https://git.drfrugal.xyz/bin/linux/x86_64/zlib-header-cli)
+[windows/x86_64/zlib-header-cli.exe](https://git.drfrugal.xyz/bin/windows/x86_64/zlib-header-cli.exe)
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
new file mode 100644
index 0000000..e84f99e
--- /dev/null
+++ b/cli/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "zlib-header-cli"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+clap = { version = "4.5.30", features = ["derive"] }
+zlib-header = { path = "../lib" }
diff --git a/cli/src/main.rs b/cli/src/main.rs
new file mode 100644
index 0000000..9392372
--- /dev/null
+++ b/cli/src/main.rs
@@ -0,0 +1,112 @@
+//! CLI to print details about the 2 Byte zlib header, as defined in
+//! [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950).
+//! This was initially written to reverse-engineer more details about Blizzard's proprietary MPQ
+//! archive format, which uses zlib streams to store data.
+//! ```
+//! Usage: zlib-header-cli [OPTIONS] [HEX4CHAR]
+//!
+//! Arguments:
+//! [HEX4CHAR] A four-character hex string representing the ZlibHeader (Big Endian)
+//!
+//! Options:
+//! -e, --explain Explain the ZlibHeader struct and abbreviations
+//! -h, --help Print help
+//! ```
+//! ```
+//! drfrugal@karazhan:~$ zlib-header-cli 789C
+//! CM 8 (DEFLATE)
+//! CINFO 7 (Window: 32768 Bytes)
+//! FCHECK 28 (valid)
+//! FDICT false (Preset Dictionary not used)
+//! FLEVEL 2 (default)
+//! ```
+//! ```
+//! drfrugal@karazhan:~$ zlib-header-cli --explain
+//! 2 Byte zlib header according to https://datatracker.ietf.org/doc/html/rfc1950
+//! 1st Byte - CMF (Compression Method and Flags)
+//! 0000_1111 CM Compression Method 8, _ (DEFLATE, UNDEFINED)
+//! 1111_0000 CINFO Compression Info window size is 2.pow(CINFO + 8)
+//! 2nd Byte - FLG (Flags)
+//! 0001_1111 FCHECK Checksum Adjustment valid if (CMF * 256 + FLG) % 31 == 0
+//! 0010_0000 FDICT Preset Dictionary a preset dictionary was used
+//! 1100_0000 FLEVEL Compression Level 0, 1, 2, 3 (fastest, fast, default, best)
+//! ```
+
+use clap::Parser;
+use zlib_header::ZlibHeader;
+
+#[derive(Debug, Parser)]
+pub struct Cli {
+ /// Explain the ZlibHeader struct and abbreviations
+ #[arg(short, long)]
+ explain: bool,
+
+ /// A four-character hex string representing the ZlibHeader (Big Endian)
+ #[arg(required_unless_present = "explain")]
+ hex4char: Option<String>,
+}
+
+pub fn main() {
+ let args = Cli::parse();
+ if args.explain {
+ explain();
+ }
+ let header = match args.hex4char {
+ Some(hex) => match ZlibHeader::from_hex(&hex) {
+ Ok(header) => header,
+ Err(err) => {
+ eprintln!("{}", err);
+ return;
+ }
+ },
+ None => {
+ return;
+ }
+ };
+ if args.explain {
+ println!();
+ }
+ let cm = header.get_cm();
+ let algorithm = header.get_cm_str();
+ let cinfo = header.get_cinfo();
+ let window = header.get_window_size();
+ let fcheck = header.get_fcheck();
+ let valid = if header.is_valid() {
+ "valid"
+ } else {
+ "not valid"
+ };
+ let fdict = header.get_fdict();
+ let dict = if fdict { "used" } else { "not used" };
+ let flevel = header.get_flevel();
+ let level = header.get_flevel_str();
+ println!("CM {} ({})", cm, algorithm);
+ println!("CINFO {} (Window: {} Bytes)", cinfo, window);
+ println!("FCHECK {} ({})", fcheck, valid);
+ println!("FDICT {} (Preset Dictionary {})", fdict, dict);
+ println!("FLEVEL {} ({})", flevel, level);
+
+ let cm = 8;
+ let cinfo = 7;
+ let fdict = false;
+ let flevel = 2;
+ let header = ZlibHeader::new(cm, cinfo, fdict, flevel);
+ match header {
+ Ok(header) => {
+ println!("header is valid (strict): {}", header.is_valid_strict()); //
+ },
+ Err(err) => eprintln!("Unable to initialize zlib header: {:?}", err)
+ }
+}
+
+/// Prints a few lines in order to explain the ZlibHeader struct.
+pub fn explain() {
+ println!("2 Byte zlib header as defined in https://datatracker.ietf.org/doc/html/rfc1950");
+ println!("1st Byte - CMF (Compression Method and Flags)");
+ println!(" 0000_1111 CM Compression Method 8, _ (DEFLATE, UNDEFINED)");
+ println!(" 1111_0000 CINFO Compression Info window size is 2.pow(CINFO + 8)");
+ println!("2nd Byte - FLG (Flags)");
+ println!(" 0001_1111 FCHECK Checksum Adjustment valid if (CMF * 256 + FLG) % 31 == 0");
+ println!(" 0010_0000 FDICT Preset Dictionary a preset dictionary was used");
+ println!(" 1100_0000 FLEVEL Compression Level 0, 1, 2, 3 (fastest, fast, default, best)");
+}
diff --git a/lib/Cargo.toml b/lib/Cargo.toml
new file mode 100644
index 0000000..0e57fb6
--- /dev/null
+++ b/lib/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "zlib-header"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+hex = "0.4.3"
diff --git a/lib/src/lib.rs b/lib/src/lib.rs
new file mode 100644
index 0000000..4cbca01
--- /dev/null
+++ b/lib/src/lib.rs
@@ -0,0 +1,282 @@
+//! Library to work with the 2 Byte zlib header, as defined in
+//! [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950).
+//! # Examples
+//! ```
+//! use zlib_header::ZlibHeader;
+//! let cm = 8;
+//! let cinfo = 7;
+//! let fdict = false;
+//! let flevel = 2;
+//! let header = ZlibHeader::new(cm, cinfo, fdict, flevel);
+//! match header {
+//! Ok(header) => {
+//! println!("header is valid (strict): {}", header.is_valid_strict()); // header is valid (strict): true
+//! },
+//! Err(err) => eprintln!("Unable to initialize zlib header: {:?}", err)
+//! }
+//! ```
+//! ```
+//! use zlib_header::ZlibHeader;
+//! let header = ZlibHeader::default();
+//! println!("Display: {}", header); // Display: 789C
+//! println!("Debug: {:?}", header); // Debug: ZlibHeader { DEFLATE | 32768 Bytes | default | Dictionary: false | valid }
+//! let bytes = [0x78, 0x9C];
+//! println!("header matches expected bytes: {}", header == bytes); // header matches expected bytes: true
+//! ```
+use hex::FromHexError;
+use std::fmt::{Debug, Display, Formatter};
+
+/// The error type when a value does not fit inside the possible range of a certain number of bits.
+#[derive(Debug)]
+pub enum OutOfRangeError {
+ CompressionMethod(String),
+ CompressionInfo(String),
+ CompressionLevel(String),
+}
+
+/// 2 Byte header at the start of a zlib stream.
+#[repr(C)]
+pub struct ZlibHeader {
+ /// Compression Method and Flags
+ /// 0000_1111 => compression method (`cm`)
+ /// 1111_0000 => compression info (`cinfo`)
+ pub cmf: u8,
+ /// Flags
+ /// 0001_1111 => checksum adjustment (`fcheck`)
+ /// 0010_0000 => preset dictionary used (`fdict`)
+ /// 1100_0000 => compression level (`flevel`)
+ pub flg: u8,
+}
+
+impl ZlibHeader {
+ /// Initializes with the given parameters and calls [`Self::set_fcheck`].
+ pub fn new(cm: u8, cinfo: u8, fdict: bool, flevel: u8) -> Result<Self, OutOfRangeError> {
+ let mut header = Self { cmf: 0, flg: 0 };
+ header.set_cm(cm)?;
+ header.set_cinfo(cinfo)?;
+ header.set_fdict(fdict);
+ header.set_flevel(flevel)?;
+ header.set_fcheck::<false>();
+ Ok(header)
+ }
+
+ /// Parses `input` as 2 Byte hex string to initialize.
+ /// # Errors
+ /// [`FromHexError::InvalidStringLength`] if `input` is not exactly 4 characters long.
+ /// Other [`FromHexError`] variants if [`hex::decode`] fails by other means.
+ pub fn from_hex(input: &str) -> Result<Self, FromHexError> {
+ if input.len() != 4 {
+ return Err(FromHexError::InvalidStringLength);
+ }
+ let bytes = hex::decode(input)?;
+ let header = Self {
+ cmf: bytes[0],
+ flg: bytes[1],
+ };
+ Ok(header)
+ }
+
+ /// Gets the lower 4 bits of `self.cmf`, representing the compression method.
+ pub fn get_cm(&self) -> u8 {
+ self.cmf & 0b0000_1111
+ }
+
+ /// Sets the lower 4 bits of `self.cmf` to `cm`, representing the compression method.
+ /// # Errors
+ /// Returns [`OutOfRangeError::CompressionInfo`] if `cm > 15`
+ pub fn set_cm(&mut self, cm: u8) -> Result<(), OutOfRangeError> {
+ if cm > 15 {
+ let msg = format!("cm was {}, but must be between 0 and 15", cm);
+ return Err(OutOfRangeError::CompressionInfo(msg));
+ }
+ self.cmf = (self.cmf & 0b1111_0000) | cm;
+ Ok(())
+ }
+
+ /// Gets the string representation of `cm`.
+ /// `DEFLATE` if it is 8, `UNDEFINED` in all other cases.
+ pub fn get_cm_str(&self) -> &str {
+ match self.get_cm() {
+ 8 => "DEFLATE",
+ _ => "UNDEFINED",
+ }
+ }
+
+ /// Gets the upper 4 bits of `self.cmf`, representing the compression info.
+ /// It is used to determine the sliding window size for de-/compression.
+ /// Read more on [`Self::get_window_size`]
+ pub fn get_cinfo(&self) -> u8 {
+ self.cmf >> 4
+ }
+
+ /// Sets the upper 4 bits of `self.cmf` to `cinfo`, representing the compression info.
+ /// # Errors
+ /// Returns [`OutOfRangeError::CompressionInfo`] if `cinfo > 15`
+ pub fn set_cinfo(&mut self, cinfo: u8) -> Result<(), OutOfRangeError> {
+ if cinfo > 15 {
+ let msg = format!("cinfo was {}, but must be between 0 and 15", cinfo);
+ return Err(OutOfRangeError::CompressionInfo(msg));
+ }
+ self.cmf = (self.cmf & 0b0000_1111) | cinfo << 4;
+ Ok(())
+ }
+
+ /// Gets the size of the sliding window in Bytes.
+ /// Valid window sizes range from 256 to 32768 - means `cinfo` ranges from 0 to 7.
+ /// The formula is: `2.pow(cinfo + 8)`
+ pub fn get_window_size(&self) -> u32 {
+ 2u32.pow(self.get_cinfo() as u32 + 8)
+ }
+
+ /// Gets the lowest 5 bits of `self.flg`, representing the checksum adjustment.
+ /// The value is chosen to satisfy the checksum formula over the entire `ZlibHeader`.
+ /// Read more on [`Self::is_valid`]
+ pub fn get_fcheck(&self) -> u8 {
+ self.flg & 0b0001_1111
+ }
+
+ /// Sets the lowest 5 bits of `self.flg`, representing the checksum adjustment.
+ /// The value is chosen to satisfy the checksum formula over the entire `ZlibHeader`.
+ /// The generic constant `CLEAN` dictates if the function has to zero the current `fcheck` bits.
+ /// Read more on [`Self::is_valid`]
+ pub fn set_fcheck<const CLEAN: bool>(&mut self) {
+ let clean_flg = match CLEAN {
+ false => self.flg,
+ true => self.flg & 0b1110_0000,
+ };
+ let clean_header: u16 = ((self.cmf as u16) << 8) + clean_flg as u16;
+ let fcheck = 31 - clean_header % 31;
+ self.flg = clean_flg | fcheck as u8;
+ }
+
+ /// Returns `true` if the checksum formula over the `ZlibHeader` is satisfied.
+ /// The formula is: `(self.cmf * 256 + self.flg) % 31 == 0`
+ pub fn is_valid(&self) -> bool {
+ (self.cmf as usize * 256 + self.flg as usize) % 31 == 0
+ }
+
+ /// In addition to [`Self::is_valid`] it also checks `cm == 8` and `cinfo <= 7`.
+ pub fn is_valid_strict(&self) -> bool {
+ let is_valid = self.is_valid();
+ let is_deflate = self.get_cm() == 8;
+ let cinfo = self.get_cinfo();
+ let is_valid_cinfo = cinfo <= 7;
+ is_valid && is_deflate && is_valid_cinfo
+ }
+
+ /// Gets the bit at index 5 of `self.flg` as `bool`, signaling the usage of a preset dictionary.
+ pub fn get_fdict(&self) -> bool {
+ (self.flg >> 5) & 1 == 1
+ }
+
+ /// Sets the bit at index 5 of `self.flg`, signaling the usage of a preset dictionary.
+ pub fn set_fdict(&mut self, fdict: bool) {
+ let mask: u8 = 0b1101_1111;
+ self.flg = (self.flg & mask) | if fdict { !mask } else { 0 };
+ }
+
+ /// Returns the upper 2 bits of `self.flg`, which represents the compression level.
+ pub fn get_flevel(&self) -> u8 {
+ self.flg >> 6
+ }
+
+ /// Sets the upper 2 bits of `self.flg` to `flevel`, which represents the compression level.
+ /// # Errors
+ /// Returns [`OutOfRangeError::CompressionLevel`] if `flevel > 3`
+ pub fn set_flevel(&mut self, flevel: u8) -> Result<(), OutOfRangeError> {
+ if flevel > 3 {
+ let msg = format!("flevel was {}, but must be between 0 and 3", flevel);
+ return Err(OutOfRangeError::CompressionInfo(msg));
+ }
+ self.flg = (self.flg & 0b0011_1111) | (flevel << 6);
+ Ok(())
+ }
+
+ /// Gets the string representation of `flevel`.
+ /// The values are: `fastest`, `fast`, `default`, `best`
+ pub fn get_flevel_str(&self) -> &str {
+ match self.get_flevel() {
+ 0 => "fastest",
+ 1 => "fast",
+ 2 => "default",
+ 3 => "best",
+ _ => unreachable!("only has 2 bits"),
+ }
+ }
+}
+
+impl PartialEq<[u8; 2]> for ZlibHeader {
+ fn eq(&self, slice: &[u8; 2]) -> bool {
+ self.cmf == slice[0] && self.flg == slice[1]
+ }
+}
+
+impl PartialEq<ZlibHeader> for [u8; 2] {
+ fn eq(&self, header: &ZlibHeader) -> bool {
+ self[0] == header.cmf && self[1] == header.flg
+ }
+}
+
+impl PartialEq<&[u8]> for ZlibHeader {
+ fn eq(&self, slice: &&[u8]) -> bool {
+ if slice.len() != 2 {
+ panic!("u8 slice must be exactly 2 Bytes when comparing ZlibHeader");
+ }
+ self.cmf == slice[0] && self.flg == slice[1]
+ }
+}
+
+impl PartialEq<ZlibHeader> for &[u8] {
+ fn eq(&self, header: &ZlibHeader) -> bool {
+ if self.len() != 2 {
+ panic!("u8 slice must be exactly 2 Bytes when comparing ZlibHeader");
+ }
+ self[0] == header.cmf && self[1] == header.flg
+ }
+}
+
+impl From<[u8; 2]> for ZlibHeader {
+ fn from(bytes: [u8; 2]) -> Self {
+ Self {
+ cmf: bytes[0],
+ flg: bytes[1],
+ }
+ }
+}
+
+impl From<ZlibHeader> for [u8; 2] {
+ fn from(header: ZlibHeader) -> Self {
+ [header.cmf, header.flg]
+ }
+}
+
+impl Default for ZlibHeader {
+ /// `789C` - this is DEFLATE with default compression level and a 32 KiB window.
+ fn default() -> Self {
+ Self {
+ cmf: 0x78,
+ flg: 0x9C,
+ }
+ }
+}
+
+impl Display for ZlibHeader {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&format!("{:02X}{:02X}", self.cmf, self.flg))
+ }
+}
+
+impl Debug for ZlibHeader {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ let cm = self.get_cm_str();
+ let window_size = self.get_window_size();
+ let flevel = self.get_flevel_str();
+ let fdict = self.get_fdict();
+ let validity = if self.is_valid() { "valid" } else { "invalid" };
+ let str = &format!(
+ "ZlibHeader {{ {} | {} Bytes | {} | Dictionary: {} | {} }}",
+ cm, window_size, flevel, fdict, validity
+ );
+ f.write_str(str)
+ }
+}
diff --git a/lib/tests/tests.rs b/lib/tests/tests.rs
new file mode 100644
index 0000000..58b0aab
--- /dev/null
+++ b/lib/tests/tests.rs
@@ -0,0 +1,59 @@
+use zlib_header::ZlibHeader;
+
+#[test]
+fn new() {
+ let header = ZlibHeader::new(9, 6, true, 0);
+ match header {
+ Ok(ok) => assert_eq!(ok.to_string(), "693B"),
+ Err(err) => {
+ panic!("{:?}", err);
+ }
+ }
+}
+
+#[test]
+fn default() {
+ let header = ZlibHeader::default();
+ assert_eq!(header.to_string(), "789C");
+ assert_eq!(header.is_valid_strict(), true);
+}
+
+#[test]
+fn eq() {
+ let header = ZlibHeader::default();
+ let bytes = [0x78, 0x9C];
+ assert_eq!(header, bytes);
+ assert_eq!(bytes, header);
+ assert_eq!(header, &bytes[..]);
+ assert_eq!(&bytes[..], header);
+}
+
+#[test]
+fn is_valid() {
+ let mut header = ZlibHeader::new(9, 6, true, 0).unwrap();
+ assert_eq!(header.is_valid(), true);
+ assert_eq!(header.is_valid_strict(), false);
+ header.set_cm(7).unwrap();
+ assert_eq!(header.is_valid(), false);
+}
+
+#[test]
+fn out_of_range() {
+ let mut header = ZlibHeader::default();
+ assert_eq!(header.set_cm(15).is_err(), false);
+ assert_eq!(header.set_cm(16).is_err(), true);
+ assert_eq!(header.set_cinfo(15).is_err(), false);
+ assert_eq!(header.set_cinfo(16).is_err(), true);
+ assert_eq!(header.set_flevel(3).is_err(), false);
+ assert_eq!(header.set_flevel(4).is_err(), true);
+}
+
+#[test]
+fn display_debug() {
+ let header = ZlibHeader::new(4, 2, true, 1).unwrap();
+ let display_debug = format!("{} {:?}", header, header);
+ assert_eq!(
+ display_debug,
+ "2473 ZlibHeader { UNDEFINED | 1024 Bytes | fast | Dictionary: true | valid }"
+ );
+}