forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

lib.rs245 lines, 8.0 KiBHistoryRawDownload
1//! DEFLATE (RFC 1951) and zlib (RFC 1950) decompression.
2//!
3//! Two entry points, both one-shot over a complete buffer: [`inflate`] for a
4//! raw DEFLATE stream (what PNG's `IDAT` chain and Matroska header stripping
5//! hand over) and [`inflate_zlib`] for the same thing inside a zlib wrapper,
6//! header checked and Adler-32 verified.
7//!
8//! Contracts worth knowing before implementing against this crate:
9//!
10//! - Every call carries a `limit`, the largest output it may produce. A stream
11//! that would exceed it stops with [`Error::LimitExceeded`]; a compressed
12//! megabyte of zeros is not allowed to become a gigabyte of memory. Pass
13//! `usize::MAX` to mean "no ceiling", and mean it.
14//! - Malformed input is an error, never a panic. Truncation is
15//! [`Error::Truncated`], anything else the format forbids is
16//! [`Error::Corrupt`] naming what was wrong.
17//! - Decoding is table-driven through a two-level lookup: no Huffman code is
18//! walked bit by bit, and the fixed trees are built once per process.
19//!
20//! Decoder state lives in one struct threaded through the block loop, so
21//! resuming across buffer boundaries stays a change to the entry points rather
22//! than a rewrite; today the public API is one-shot because both callers are.
23//!
24//! The encoder side ([`deflate_raw`], [`deflate_zlib`]) is a simple greedy LZ77 with
25//! fixed Huffman codes, enough for PNG output; it does not aim to match zlib's ratio.
26//!
27//! No async, no unsafe, no external dependencies.
28
29#![forbid(unsafe_code)]
30#![warn(missing_docs)]
31
32mod bits;
33mod huffman;
34mod deflate;
35mod inflate;
36
37use std::fmt;
38
39use bits::Bits;
40
41pub use deflate::{deflate_raw, deflate_zlib};
42
43/// Everything a compressed stream can get wrong.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum Error {
46 /// The stream ended in the middle of a code, a block or the trailer.
47 Truncated,
48 /// The stream violates RFC 1950/1951.
49 Corrupt {
50 /// What was wrong, e.g. "over-subscribed Huffman code".
51 context: String,
52 },
53 /// Decompressing further would pass the caller's ceiling.
54 LimitExceeded {
55 /// The ceiling that was hit, in bytes.
56 limit: usize,
57 },
58 /// The zlib trailer disagrees with the data that was decompressed.
59 Adler32Mismatch {
60 /// Checksum stored in the trailer.
61 expected: u32,
62 /// Checksum of the output actually produced.
63 actual: u32,
64 },
65 /// A zlib feature this crate does not implement.
66 Unsupported {
67 /// The construct that was refused, e.g. "zlib preset dictionary".
68 what: String,
69 /// Why it is refused.
70 why: String,
71 },
72}
73
74impl Error {
75 fn corrupt(context: impl Into<String>) -> Error {
76 Error::Corrupt {
77 context: context.into(),
78 }
79 }
80}
81
82impl fmt::Display for Error {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 match self {
85 Error::Truncated => write!(f, "truncated deflate stream"),
86 Error::Corrupt { context } => write!(f, "corrupt deflate stream: {context}"),
87 Error::LimitExceeded { limit } => {
88 write!(f, "decompressed output exceeded the {limit} byte limit")
89 }
90 Error::Adler32Mismatch { expected, actual } => write!(
91 f,
92 "zlib adler32 mismatch: stream says {expected:#010x}, output is {actual:#010x}"
93 ),
94 Error::Unsupported { what, why } => write!(f, "unsupported {what}: {why}"),
95 }
96 }
97}
98
99impl std::error::Error for Error {}
100
101impl From<Error> for ec_core::Error {
102 fn from(error: Error) -> ec_core::Error {
103 match error {
104 Error::Truncated => ec_core::Error::NeedMore,
105 Error::Unsupported { what, why } => ec_core::Error::Unsupported { what, why },
106 other => ec_core::Error::corrupt(other.to_string()),
107 }
108 }
109}
110
111/// Which wrapper, if any, surrounds the DEFLATE data.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum Format {
114 /// Bare RFC 1951 blocks.
115 Raw,
116 /// RFC 1950: two header bytes, the blocks, an Adler-32 trailer.
117 Zlib,
118}
119
120/// Decompress a raw DEFLATE stream, producing at most `limit` bytes.
121pub fn inflate(input: &[u8], limit: usize) -> Result<Vec<u8>, Error> {
122 let mut out = Vec::new();
123 inflate_into(input, &mut out, limit, Format::Raw)?;
124 Ok(out)
125}
126
127/// Decompress a zlib stream, producing at most `limit` bytes.
128///
129/// The two header bytes are checked and the Adler-32 trailer is verified
130/// against the output.
131pub fn inflate_zlib(input: &[u8], limit: usize) -> Result<Vec<u8>, Error> {
132 let mut out = Vec::new();
133 inflate_into(input, &mut out, limit, Format::Zlib)?;
134 Ok(out)
135}
136
137/// Decompress onto the end of an existing buffer.
138///
139/// `limit` bounds the total length of `out`, not the bytes added. On failure
140/// `out` keeps whatever was decompressed before the error, which is what a
141/// caller reporting partial progress wants.
142pub fn inflate_into(
143 input: &[u8],
144 out: &mut Vec<u8>,
145 limit: usize,
146 format: Format,
147) -> Result<(), Error> {
148 let start = out.len();
149 let body = match format {
150 Format::Raw => input,
151 Format::Zlib => zlib_header(input)?,
152 };
153 let mut bits = Bits::new(body);
154 let end = inflate::blocks(&mut bits, out, limit)?;
155 if format == Format::Zlib {
156 let trailer: [u8; 4] = body
157 .get(end..)
158 .and_then(|rest| rest.get(..4))
159 .ok_or(Error::Truncated)?
160 .try_into()
161 .expect("a four byte slice");
162 let expected = u32::from_be_bytes(trailer);
163 let actual = adler32(&out[start..]);
164 if expected != actual {
165 return Err(Error::Adler32Mismatch { expected, actual });
166 }
167 }
168 Ok(())
169}
170
171/// Validate the RFC 1950 header and hand back the DEFLATE data behind it.
172fn zlib_header(input: &[u8]) -> Result<&[u8], Error> {
173 let (&cmf, &flg) = match (input.first(), input.get(1)) {
174 (Some(cmf), Some(flg)) => (cmf, flg),
175 _ => return Err(Error::Truncated),
176 };
177 if cmf & 0x0f != 8 {
178 return Err(Error::corrupt("zlib compression method is not deflate"));
179 }
180 if cmf >> 4 > 7 {
181 return Err(Error::corrupt("zlib window size above 32 KiB"));
182 }
183 if !(cmf as u16 * 256 + flg as u16).is_multiple_of(31) {
184 return Err(Error::corrupt("zlib header check bits do not divide by 31"));
185 }
186 if flg & 0x20 != 0 {
187 return Err(Error::Unsupported {
188 what: "zlib preset dictionary".into(),
189 why: "no caller in this family uses FDICT".into(),
190 });
191 }
192 Ok(&input[2..])
193}
194
195/// RFC 1950 §9. Chunked so the sums cannot overflow between reductions.
196fn adler32(data: &[u8]) -> u32 {
197 const BASE: u32 = 65521;
198 let (mut a, mut b) = (1u32, 0u32);
199 for chunk in data.chunks(5552) {
200 for &byte in chunk {
201 a += byte as u32;
202 b += a;
203 }
204 a %= BASE;
205 b %= BASE;
206 }
207 (b << 16) | a
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 #[test]
215 fn adler32_matches_the_rfc_example() {
216 // zlib's own documented value for "abc" and the empty string.
217 assert_eq!(adler32(b""), 1);
218 assert_eq!(adler32(b"abc"), 0x024d_0127);
219 // Long input exercises the chunked reduction.
220 assert_eq!(adler32(&vec![0xa5; 100_000]), 0x5afa_d3d6);
221 }
222
223 #[test]
224 fn zlib_header_is_checked() {
225 assert!(matches!(zlib_header(&[]), Err(Error::Truncated)));
226 assert!(matches!(zlib_header(&[0x78]), Err(Error::Truncated)));
227 assert!(matches!(
228 zlib_header(&[0x79, 0x9c]),
229 Err(Error::Corrupt { .. })
230 ));
231 assert!(matches!(
232 zlib_header(&[0x88, 0x9c]),
233 Err(Error::Corrupt { .. })
234 ));
235 assert!(matches!(
236 zlib_header(&[0x78, 0x9d]),
237 Err(Error::Corrupt { .. })
238 ));
239 assert!(matches!(
240 zlib_header(&[0x78, 0xbb]),
241 Err(Error::Unsupported { .. })
242 ));
243 assert_eq!(zlib_header(&[0x78, 0x9c, 1, 2]).unwrap(), &[1, 2]);
244 }
245}