Skip to main content

numcodecs_zlib/
lib.rs

1//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io] [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
2//!
3//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/numcodecs-rs/ci.yml?branch=main
4//! [workflow]: https://github.com/juntyr/numcodecs-rs/actions/workflows/ci.yml?query=branch%3Amain
5//!
6//! [MSRV]: https://img.shields.io/badge/MSRV-1.88.0-blue
7//! [repo]: https://github.com/juntyr/numcodecs-rs
8//!
9//! [Latest Version]: https://img.shields.io/crates/v/numcodecs-zlib
10//! [crates.io]: https://crates.io/crates/numcodecs-zlib
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-zlib
13//! [docs.rs]: https://docs.rs/numcodecs-zlib/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_zlib
17//!
18//! Zlib codec implementation for the [`numcodecs`] API.
19
20#![allow(clippy::multiple_crate_versions)] // embedded-io
21
22use std::borrow::Cow;
23
24use ndarray::Array1;
25use numcodecs::{
26    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
27    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
28};
29use schemars::{JsonSchema, JsonSchema_repr};
30use serde::{Deserialize, Serialize};
31use serde_repr::{Deserialize_repr, Serialize_repr};
32use thiserror::Error;
33
34#[cfg(test)]
35use ::serde_json as _;
36
37type ZlibCodecVersion = StaticCodecVersion<0, 1, 0>;
38
39#[derive(Clone, Serialize, Deserialize, JsonSchema)]
40#[serde(deny_unknown_fields)]
41/// Codec providing compression using Zlib
42pub struct ZlibCodec {
43    /// Zlib compression level.
44    ///
45    /// The level ranges from 0, no compression, to 9, best compression.
46    pub level: ZlibLevel,
47    /// The codec's encoding format version. Do not provide this parameter explicitly.
48    #[serde(default, rename = "_version")]
49    pub version: ZlibCodecVersion,
50}
51
52#[derive(Copy, Clone, Serialize_repr, Deserialize_repr, JsonSchema_repr)]
53#[repr(u8)]
54#[schemars(inline)]
55/// Zlib compression level.
56///
57/// The level ranges from 0, no compression, to 9, best compression.
58#[expect(missing_docs)]
59pub enum ZlibLevel {
60    ZNoCompression = 0,
61    ZBestSpeed = 1,
62    ZLevel2 = 2,
63    ZLevel3 = 3,
64    ZLevel4 = 4,
65    ZLevel5 = 5,
66    ZLevel6 = 6,
67    ZLevel7 = 7,
68    ZLevel8 = 8,
69    ZBestCompression = 9,
70}
71
72impl Codec for ZlibCodec {
73    type Error = ZlibCodecError;
74
75    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
76        compress(data.view(), self.level)
77            .map(|bytes| AnyArray::U8(Array1::from_vec(bytes).into_dyn()))
78    }
79
80    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
81        let AnyCowArray::U8(encoded) = encoded else {
82            return Err(ZlibCodecError::EncodedDataNotBytes {
83                dtype: encoded.dtype(),
84            });
85        };
86
87        if !matches!(encoded.shape(), [_]) {
88            return Err(ZlibCodecError::EncodedDataNotOneDimensional {
89                shape: encoded.shape().to_vec(),
90            });
91        }
92
93        decompress(&AnyCowArray::U8(encoded).as_bytes())
94    }
95
96    fn decode_into(
97        &self,
98        encoded: AnyArrayView,
99        decoded: AnyArrayViewMut,
100    ) -> Result<(), Self::Error> {
101        let AnyArrayView::U8(encoded) = encoded else {
102            return Err(ZlibCodecError::EncodedDataNotBytes {
103                dtype: encoded.dtype(),
104            });
105        };
106
107        if !matches!(encoded.shape(), [_]) {
108            return Err(ZlibCodecError::EncodedDataNotOneDimensional {
109                shape: encoded.shape().to_vec(),
110            });
111        }
112
113        decompress_into(&AnyArrayView::U8(encoded).as_bytes(), decoded)
114    }
115}
116
117impl StaticCodec for ZlibCodec {
118    const CODEC_ID: &'static str = "zlib.rs";
119
120    type Config<'de> = Self;
121
122    fn from_config(config: Self::Config<'_>) -> Self {
123        config
124    }
125
126    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
127        StaticCodecConfig::from(self)
128    }
129}
130
131#[derive(Debug, Error)]
132/// Errors that may occur when applying the [`ZlibCodec`].
133pub enum ZlibCodecError {
134    /// [`ZlibCodec`] failed to encode the header
135    #[error("Zlib failed to encode the header")]
136    HeaderEncodeFailed {
137        /// Opaque source error
138        source: ZlibHeaderError,
139    },
140    /// [`ZlibCodec`] can only decode one-dimensional byte arrays but received
141    /// an array of a different dtype
142    #[error(
143        "Zlib can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
144    )]
145    EncodedDataNotBytes {
146        /// The unexpected dtype of the encoded array
147        dtype: AnyArrayDType,
148    },
149    /// [`ZlibCodec`] can only decode one-dimensional byte arrays but received
150    /// an array of a different shape
151    #[error(
152        "Zlib can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
153    )]
154    EncodedDataNotOneDimensional {
155        /// The unexpected shape of the encoded array
156        shape: Vec<usize>,
157    },
158    /// [`ZlibCodec`] failed to encode the header
159    #[error("Zlib failed to decode the header")]
160    HeaderDecodeFailed {
161        /// Opaque source error
162        source: ZlibHeaderError,
163    },
164    /// [`ZlibCodec`] decode consumed less encoded data, which contains trailing
165    /// junk
166    #[error("Zlib decode consumed less encoded data, which contains trailing junk")]
167    DecodeExcessiveEncodedData,
168    /// [`ZlibCodec`] produced less decoded data than expected
169    #[error("Zlib produced less decoded data than expected")]
170    DecodeProducedLess,
171    /// [`ZlibCodec`] failed to decode the encoded data
172    #[error("Zlib failed to decode the encoded data")]
173    ZlibDecodeFailed {
174        /// Opaque source error
175        source: ZlibDecodeError,
176    },
177    /// [`ZlibCodec`] cannot decode into the provided array
178    #[error("Zlib cannot decode into the provided array")]
179    MismatchedDecodeIntoArray {
180        /// The source of the error
181        #[from]
182        source: AnyArrayAssignError,
183    },
184}
185
186#[derive(Debug, Error)]
187#[error(transparent)]
188/// Opaque error for when encoding or decoding the header fails
189pub struct ZlibHeaderError(postcard::Error);
190
191#[derive(Debug, Error)]
192#[error(transparent)]
193/// Opaque error for when decoding with Zlib fails
194pub struct ZlibDecodeError(miniz_oxide::inflate::DecompressError);
195
196#[expect(clippy::needless_pass_by_value)]
197/// Compress the `array` using Zlib with the provided `level`.
198///
199/// # Errors
200///
201/// Errors with [`ZlibCodecError::HeaderEncodeFailed`] if encoding the header
202/// to the output bytevec failed.
203///
204/// # Panics
205///
206/// Panics if the infallible encoding with Zlib fails.
207pub fn compress(array: AnyArrayView, level: ZlibLevel) -> Result<Vec<u8>, ZlibCodecError> {
208    let data = array.as_bytes();
209
210    let mut encoded = postcard::to_extend(
211        &CompressionHeader {
212            dtype: array.dtype(),
213            shape: Cow::Borrowed(array.shape()),
214            version: StaticCodecVersion,
215        },
216        Vec::new(),
217    )
218    .map_err(|err| ZlibCodecError::HeaderEncodeFailed {
219        source: ZlibHeaderError(err),
220    })?;
221
222    let mut in_pos = 0;
223    let mut out_pos = encoded.len();
224
225    // The comp flags function sets the zlib flag if the window_bits parameter
226    //  is > 0.
227    let flags =
228        miniz_oxide::deflate::core::create_comp_flags_from_zip_params((level as u8).into(), 1, 0);
229    let mut compressor = miniz_oxide::deflate::core::CompressorOxide::new(flags);
230    encoded.resize(encoded.len() + (data.len() / 2).max(2), 0);
231
232    loop {
233        let (Some(data_left), Some(encoded_left)) =
234            (data.get(in_pos..), encoded.get_mut(out_pos..))
235        else {
236            #[expect(clippy::panic)] // this would be a bug and cannot be user-caused
237            {
238                panic!("Zlib encode bug: input or output is out of bounds")
239            }
240        };
241
242        let (status, bytes_in, bytes_out) = miniz_oxide::deflate::core::compress(
243            &mut compressor,
244            data_left,
245            encoded_left,
246            miniz_oxide::deflate::core::TDEFLFlush::Finish,
247        );
248
249        out_pos += bytes_out;
250        in_pos += bytes_in;
251
252        match status {
253            miniz_oxide::deflate::core::TDEFLStatus::Okay => {
254                // We need more space, so resize the vector.
255                if encoded.len().saturating_sub(out_pos) < 30 {
256                    encoded.resize(encoded.len() * 2, 0);
257                }
258            }
259            miniz_oxide::deflate::core::TDEFLStatus::Done => {
260                encoded.truncate(out_pos);
261
262                assert!(
263                    in_pos == data.len(),
264                    "Zlib encode bug: consumed less input than expected"
265                );
266
267                return Ok(encoded);
268            }
269            #[expect(clippy::panic)] // this would be a bug and cannot be user-caused
270            err => panic!("Zlib encode bug: {err:?}"),
271        }
272    }
273}
274
275/// Decompress the `encoded` data into an array using Zlib.
276///
277/// # Errors
278///
279/// Errors with
280/// - [`ZlibCodecError::HeaderDecodeFailed`] if decoding the header failed
281/// - [`ZlibCodecError::DecodeExcessiveEncodedData`] if the encoded data
282///   contains excessive trailing data junk
283/// - [`ZlibCodecError::DecodeProducedLess`] if decoding produced less data than
284///   expected
285/// - [`ZlibCodecError::ZlibDecodeFailed`] if an opaque decoding error occurred
286pub fn decompress(encoded: &[u8]) -> Result<AnyArray, ZlibCodecError> {
287    let (header, encoded) =
288        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
289            ZlibCodecError::HeaderDecodeFailed {
290                source: ZlibHeaderError(err),
291            }
292        })?;
293
294    let (decoded, result) = AnyArray::with_zeros_bytes(header.dtype, &header.shape, |decoded| {
295        decompress_into_bytes(encoded, decoded)
296    });
297
298    result.map(|()| decoded)
299}
300
301/// Decompress the `encoded` data into a `decoded` array using Zlib.
302///
303/// # Errors
304///
305/// Errors with
306/// - [`ZlibCodecError::HeaderDecodeFailed`] if decoding the header failed
307/// - [`ZlibCodecError::MismatchedDecodeIntoArray`] if the `decoded` array is of
308///   the wrong dtype or shape
309/// - [`ZlibCodecError::HeaderDecodeFailed`] if decoding the header failed
310/// - [`ZlibCodecError::DecodeExcessiveEncodedData`] if the encoded data
311///   contains excessive trailing data junk
312/// - [`ZlibCodecError::DecodeProducedLess`] if decoding produced less data than
313///   expected
314/// - [`ZlibCodecError::ZlibDecodeFailed`] if an opaque decoding error occurred
315pub fn decompress_into(encoded: &[u8], mut decoded: AnyArrayViewMut) -> Result<(), ZlibCodecError> {
316    let (header, encoded) =
317        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
318            ZlibCodecError::HeaderDecodeFailed {
319                source: ZlibHeaderError(err),
320            }
321        })?;
322
323    if header.dtype != decoded.dtype() {
324        return Err(ZlibCodecError::MismatchedDecodeIntoArray {
325            source: AnyArrayAssignError::DTypeMismatch {
326                src: header.dtype,
327                dst: decoded.dtype(),
328            },
329        });
330    }
331
332    if header.shape != decoded.shape() {
333        return Err(ZlibCodecError::MismatchedDecodeIntoArray {
334            source: AnyArrayAssignError::ShapeMismatch {
335                src: header.shape.into_owned(),
336                dst: decoded.shape().to_vec(),
337            },
338        });
339    }
340
341    decoded.with_bytes_mut(|decoded| decompress_into_bytes(encoded, decoded))
342}
343
344fn decompress_into_bytes(encoded: &[u8], decoded: &mut [u8]) -> Result<(), ZlibCodecError> {
345    let flags = miniz_oxide::inflate::core::inflate_flags::TINFL_FLAG_PARSE_ZLIB_HEADER
346        | miniz_oxide::inflate::core::inflate_flags::TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
347
348    let mut decomp = Box::<miniz_oxide::inflate::core::DecompressorOxide>::default();
349
350    let (status, in_consumed, out_consumed) =
351        miniz_oxide::inflate::core::decompress(&mut decomp, encoded, decoded, 0, flags);
352
353    match status {
354        miniz_oxide::inflate::TINFLStatus::Done => {
355            if in_consumed != encoded.len() {
356                Err(ZlibCodecError::DecodeExcessiveEncodedData)
357            } else if out_consumed == decoded.len() {
358                Ok(())
359            } else {
360                Err(ZlibCodecError::DecodeProducedLess)
361            }
362        }
363        status => Err(ZlibCodecError::ZlibDecodeFailed {
364            source: ZlibDecodeError(miniz_oxide::inflate::DecompressError {
365                status,
366                output: Vec::new(),
367            }),
368        }),
369    }
370}
371
372#[derive(Serialize, Deserialize)]
373struct CompressionHeader<'a> {
374    dtype: AnyArrayDType,
375    #[serde(borrow)]
376    shape: Cow<'a, [usize]>,
377    version: ZlibCodecVersion,
378}