Skip to main content

rusty_zlib/
lib.rs

1#![doc = core::include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3// House delta: the default build no longer compiles the C allocator, which leaves parts of the
4// shared allocator and C-API plumbing unused. Upstream's reduced-feature builds were never
5// warning-clean either. Dead-code lints are enforced in the full-feature build (both allocators:
6// tests, CI and libz-rs-sys).
7#![cfg_attr(
8    not(all(feature = "c-allocator", feature = "rust-allocator")),
9    allow(dead_code, unused_imports)
10)]
11
12#[cfg(any(feature = "rust-allocator", feature = "c-allocator"))]
13extern crate alloc;
14
15pub mod adler32;
16pub mod compat;
17pub mod crc32;
18
19cfg_select! {
20    feature = "__internal-api" => {
21        pub mod allocate;
22        pub mod c_api;
23        pub mod deflate;
24        pub mod inflate;
25
26        pub const MIN_WBITS: i32 = 8; // 256b LZ77 window
27        pub const MAX_WBITS: i32 = 15; // 32kb LZ77 window
28    }
29    _ => {
30        pub(crate) mod allocate;
31        pub(crate) mod c_api;
32        pub(crate) mod deflate;
33        pub(crate) mod inflate;
34
35        pub(crate) const MIN_WBITS: i32 = 8; // 256b LZ77 window
36        pub(crate) const MAX_WBITS: i32 = 15; // 32kb LZ77 window
37    }
38}
39
40mod cpu_features;
41mod stable;
42mod weak_slice;
43
44pub use cpu_features::simd_path;
45pub use stable::{Deflate, DeflateError, Inflate, InflateError, Status};
46
47pub use deflate::{
48    default_level_table, set_default_level_table, DeflateConfig, LevelTable, Method, Strategy,
49};
50pub use inflate::InflateConfig;
51
52pub use deflate::{compress_bound, compress_slice};
53pub use inflate::decompress_slice;
54
55macro_rules! traceln {
56    ($($arg:tt)*) => {
57        #[cfg(feature = "ZLIB_DEBUG")]
58        {
59            eprintln!($($arg)*)
60        }
61    };
62}
63pub(crate) use traceln;
64
65macro_rules! trace {
66    ($($arg:tt)*) => {
67        #[cfg(feature = "ZLIB_DEBUG")]
68        {
69            eprint!($($arg)*)
70        }
71    };
72}
73pub(crate) use trace;
74
75macro_rules! cfg_select {
76    ({ $($tt:tt)* }) => {{
77        $crate::cfg_select! { $($tt)* }
78    }};
79    (_ => { $($output:tt)* }) => {
80        $($output)*
81    };
82    (
83        $cfg:meta => $output:tt
84        $($( $rest:tt )+)?
85    ) => {
86        #[cfg($cfg)]
87        $crate::cfg_select! { _ => $output }
88        $(
89            #[cfg(not($cfg))]
90            $crate::cfg_select! { $($rest)+ }
91        )?
92    }
93}
94use cfg_select;
95
96/// Maximum size of the dynamic table.  The maximum number of code structures is
97/// 1924, which is the sum of 1332 for literal/length codes and 592 for distance
98/// codes.  These values were found by exhaustive searches using the program
99/// examples/enough.c found in the zlib distributions.  The arguments to that
100/// program are the number of symbols, the initial root table size, and the
101/// maximum bit length of a code.  "enough 286 10 15" for literal/length codes
102/// returns 1332, and "enough 30 9 15" for distance codes returns 592.
103/// The initial root table size (10 or 9) is found in the fifth argument of the
104/// inflate_table() calls in inflate.c and infback.c.  If the root table size is
105/// changed, then these maximum sizes would be need to be recalculated and
106/// updated.
107#[allow(unused)]
108pub(crate) const ENOUGH: usize = ENOUGH_LENS + ENOUGH_DISTS;
109pub(crate) const ENOUGH_LENS: usize = 1332;
110pub(crate) const ENOUGH_DISTS: usize = 592;
111
112/// initial adler-32 hash value
113pub(crate) const ADLER32_INITIAL_VALUE: usize = 1;
114/// initial crc-32 hash value
115pub(crate) const CRC32_INITIAL_VALUE: u32 = 0;
116
117pub(crate) const DEF_WBITS: i32 = MAX_WBITS;
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
120#[cfg_attr(feature = "__internal-fuzz", derive(arbitrary::Arbitrary))]
121pub enum DeflateFlush {
122    #[default]
123    /// if flush is set to `NoFlush`, that allows deflate to decide how much data
124    /// to accumulate before producing output, in order to maximize compression.
125    NoFlush = 0,
126
127    /// If flush is set to `PartialFlush`, all pending output is flushed to the
128    /// output buffer, but the output is not aligned to a byte boundary.  All of the
129    /// input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
130    /// This completes the current deflate block and follows it with an empty fixed
131    /// codes block that is 10 bits long.  This assures that enough bytes are output
132    /// in order for the decompressor to finish the block before the empty fixed
133    /// codes block.
134    PartialFlush = 1,
135
136    /// If the parameter flush is set to `SyncFlush`, all pending output is
137    /// flushed to the output buffer and the output is aligned on a byte boundary, so
138    /// that the decompressor can get all input data available so far.  (In
139    /// particular avail_in is zero after the call if enough output space has been
140    /// provided before the call.) Flushing may degrade compression for some
141    /// compression algorithms and so it should be used only when necessary.  This
142    /// completes the current deflate block and follows it with an empty stored block
143    /// that is three bits plus filler bits to the next byte, followed by four bytes
144    /// (00 00 ff ff).
145    SyncFlush = 2,
146
147    /// If flush is set to `FullFlush`, all output is flushed as with
148    /// Z_SYNC_FLUSH, and the compression state is reset so that decompression can
149    /// restart from this point if previous compressed data has been damaged or if
150    /// random access is desired.  Using `FullFlush` too often can seriously degrade
151    /// compression.
152    FullFlush = 3,
153
154    /// If the parameter flush is set to `Finish`, pending input is processed,
155    /// pending output is flushed and deflate returns with `StreamEnd` if there was
156    /// enough output space.  If deflate returns with `Ok` or `BufError`, this
157    /// function must be called again with `Finish` and more output space (updated
158    /// avail_out) but no more input data, until it returns with `StreamEnd` or an
159    /// error.  After deflate has returned `StreamEnd`, the only possible operations
160    /// on the stream are deflateReset or deflateEnd.
161    ///
162    /// `Finish` can be used in the first deflate call after deflateInit if all the
163    /// compression is to be done in a single step.  In order to complete in one
164    /// call, avail_out must be at least the value returned by deflateBound (see
165    /// below).  Then deflate is guaranteed to return `StreamEnd`.  If not enough
166    /// output space is provided, deflate will not return `StreamEnd`, and it must
167    /// be called again as described above.
168    Finish = 4,
169
170    /// If flush is set to `Block`, a deflate block is completed and emitted, as
171    /// for `SyncFlush`, but the output is not aligned on a byte boundary, and up to
172    /// seven bits of the current block are held to be written as the next byte after
173    /// the next deflate block is completed.  In this case, the decompressor may not
174    /// be provided enough bits at this point in order to complete decompression of
175    /// the data provided so far to the compressor.  It may need to wait for the next
176    /// block to be emitted.  This is for advanced applications that need to control
177    /// the emission of deflate blocks.
178    Block = 5,
179}
180
181impl TryFrom<i32> for DeflateFlush {
182    type Error = ();
183
184    fn try_from(value: i32) -> Result<Self, Self::Error> {
185        match value {
186            0 => Ok(Self::NoFlush),
187            1 => Ok(Self::PartialFlush),
188            2 => Ok(Self::SyncFlush),
189            3 => Ok(Self::FullFlush),
190            4 => Ok(Self::Finish),
191            5 => Ok(Self::Block),
192            _ => Err(()),
193        }
194    }
195}
196
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
198pub enum InflateFlush {
199    #[default]
200    NoFlush = 0,
201    SyncFlush = 2,
202    Finish = 4,
203    Block = 5,
204    Trees = 6,
205}
206
207impl TryFrom<i32> for InflateFlush {
208    type Error = ();
209
210    fn try_from(value: i32) -> Result<Self, Self::Error> {
211        match value {
212            0 => Ok(Self::NoFlush),
213            2 => Ok(Self::SyncFlush),
214            4 => Ok(Self::Finish),
215            5 => Ok(Self::Block),
216            6 => Ok(Self::Trees),
217            _ => Err(()),
218        }
219    }
220}
221
222#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
223pub(crate) struct Code {
224    /// operation, extra bits, table bits
225    pub op: u8,
226    /// bits in this part of the code
227    pub bits: u8,
228    /// offset in table or code value
229    pub val: u16,
230}
231
232#[derive(Debug, Copy, Clone, PartialEq, Eq)]
233#[repr(i32)]
234pub enum ReturnCode {
235    Ok = 0,
236    StreamEnd = 1,
237    NeedDict = 2,
238    ErrNo = -1,
239    StreamError = -2,
240    DataError = -3,
241    MemError = -4,
242    BufError = -5,
243    VersionError = -6,
244}
245
246impl From<i32> for ReturnCode {
247    fn from(value: i32) -> Self {
248        match Self::try_from_c_int(value) {
249            Some(value) => value,
250            None => panic!("invalid return code {value}"),
251        }
252    }
253}
254
255impl ReturnCode {
256    fn error_message_str(self) -> &'static str {
257        self.error_message_str_with_null().trim_end_matches('\0')
258    }
259
260    const fn error_message_str_with_null(self) -> &'static str {
261        match self {
262            ReturnCode::Ok => "\0",
263            ReturnCode::StreamEnd => "stream end\0",
264            ReturnCode::NeedDict => "need dictionary\0",
265            ReturnCode::ErrNo => "file error\0",
266            ReturnCode::StreamError => "stream error\0",
267            ReturnCode::DataError => "data error\0",
268            ReturnCode::MemError => "insufficient memory\0",
269            ReturnCode::BufError => "buffer error\0",
270            ReturnCode::VersionError => "incompatible version\0",
271        }
272    }
273
274    pub const fn error_message(self) -> *const core::ffi::c_char {
275        let msg = self.error_message_str_with_null();
276        msg.as_ptr().cast::<core::ffi::c_char>()
277    }
278
279    pub const fn try_from_c_int(err: core::ffi::c_int) -> Option<Self> {
280        match err {
281            0 => Some(Self::Ok),
282            1 => Some(Self::StreamEnd),
283            2 => Some(Self::NeedDict),
284            -1 => Some(Self::ErrNo),
285            -2 => Some(Self::StreamError),
286            -3 => Some(Self::DataError),
287            -4 => Some(Self::MemError),
288            -5 => Some(Self::BufError),
289            -6 => Some(Self::VersionError),
290            _ => None,
291        }
292    }
293}