1#![allow(clippy::multiple_crate_versions)] use 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)]
41pub struct ZlibCodec {
43 pub level: ZlibLevel,
47 #[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#[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)]
132pub enum ZlibCodecError {
134 #[error("Zlib failed to encode the header")]
136 HeaderEncodeFailed {
137 source: ZlibHeaderError,
139 },
140 #[error(
143 "Zlib can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
144 )]
145 EncodedDataNotBytes {
146 dtype: AnyArrayDType,
148 },
149 #[error(
152 "Zlib can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
153 )]
154 EncodedDataNotOneDimensional {
155 shape: Vec<usize>,
157 },
158 #[error("Zlib failed to decode the header")]
160 HeaderDecodeFailed {
161 source: ZlibHeaderError,
163 },
164 #[error("Zlib decode consumed less encoded data, which contains trailing junk")]
167 DecodeExcessiveEncodedData,
168 #[error("Zlib produced less decoded data than expected")]
170 DecodeProducedLess,
171 #[error("Zlib failed to decode the encoded data")]
173 ZlibDecodeFailed {
174 source: ZlibDecodeError,
176 },
177 #[error("Zlib cannot decode into the provided array")]
179 MismatchedDecodeIntoArray {
180 #[from]
182 source: AnyArrayAssignError,
183 },
184}
185
186#[derive(Debug, Error)]
187#[error(transparent)]
188pub struct ZlibHeaderError(postcard::Error);
190
191#[derive(Debug, Error)]
192#[error(transparent)]
193pub struct ZlibDecodeError(miniz_oxide::inflate::DecompressError);
195
196#[expect(clippy::needless_pass_by_value)]
197pub 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 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)] {
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 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)] err => panic!("Zlib encode bug: {err:?}"),
271 }
272 }
273}
274
275pub 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
301pub 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}