Skip to main content

numcodecs_zstd/
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-zstd
10//! [crates.io]: https://crates.io/crates/numcodecs-zstd
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-zstd
13//! [docs.rs]: https://docs.rs/numcodecs-zstd/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_zstd
17//!
18//! Zstandard codec implementation for the [`numcodecs`] API.
19
20#![allow(clippy::multiple_crate_versions)] // embedded-io
21
22use std::{borrow::Cow, io};
23
24use ndarray::Array1;
25use numcodecs::{
26    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
27    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
28};
29use schemars::JsonSchema;
30use serde::{Deserialize, Deserializer, Serialize, Serializer};
31use thiserror::Error;
32// Only used to explicitly enable the `no_wasm_shim` feature in zstd/zstd-sys
33use zstd_sys as _;
34
35#[cfg(test)]
36use ::serde_json as _;
37
38type ZstdCodecVersion = StaticCodecVersion<0, 1, 0>;
39
40#[derive(Clone, Serialize, Deserialize, JsonSchema)]
41#[serde(deny_unknown_fields)]
42/// Codec providing compression using Zstandard
43pub struct ZstdCodec {
44    /// Zstandard compression level.
45    ///
46    /// The level ranges from small (fastest) to large (best compression).
47    pub level: ZstdLevel,
48    /// The codec's encoding format version. Do not provide this parameter explicitly.
49    #[serde(default, rename = "_version")]
50    pub version: ZstdCodecVersion,
51}
52
53impl Codec for ZstdCodec {
54    type Error = ZstdCodecError;
55
56    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
57        compress(data.view(), self.level)
58            .map(|bytes| AnyArray::U8(Array1::from_vec(bytes).into_dyn()))
59    }
60
61    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
62        let AnyCowArray::U8(encoded) = encoded else {
63            return Err(ZstdCodecError::EncodedDataNotBytes {
64                dtype: encoded.dtype(),
65            });
66        };
67
68        if !matches!(encoded.shape(), [_]) {
69            return Err(ZstdCodecError::EncodedDataNotOneDimensional {
70                shape: encoded.shape().to_vec(),
71            });
72        }
73
74        decompress(&AnyCowArray::U8(encoded).as_bytes())
75    }
76
77    fn decode_into(
78        &self,
79        encoded: AnyArrayView,
80        decoded: AnyArrayViewMut,
81    ) -> Result<(), Self::Error> {
82        let AnyArrayView::U8(encoded) = encoded else {
83            return Err(ZstdCodecError::EncodedDataNotBytes {
84                dtype: encoded.dtype(),
85            });
86        };
87
88        if !matches!(encoded.shape(), [_]) {
89            return Err(ZstdCodecError::EncodedDataNotOneDimensional {
90                shape: encoded.shape().to_vec(),
91            });
92        }
93
94        decompress_into(&AnyArrayView::U8(encoded).as_bytes(), decoded)
95    }
96}
97
98impl StaticCodec for ZstdCodec {
99    const CODEC_ID: &'static str = "zstd.rs";
100
101    type Config<'de> = Self;
102
103    fn from_config(config: Self::Config<'_>) -> Self {
104        config
105    }
106
107    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
108        StaticCodecConfig::from(self)
109    }
110}
111
112#[derive(Clone, Copy, JsonSchema)]
113#[schemars(transparent)]
114#[schemars(inline)]
115/// Zstandard compression level.
116///
117/// The level ranges from small (fastest) to large (best compression).
118pub struct ZstdLevel {
119    level: zstd::zstd_safe::CompressionLevel,
120}
121
122impl Serialize for ZstdLevel {
123    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
124        self.level.serialize(serializer)
125    }
126}
127
128impl<'de> Deserialize<'de> for ZstdLevel {
129    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
130        let level = Deserialize::deserialize(deserializer)?;
131
132        let level_range = zstd::compression_level_range();
133
134        if !level_range.contains(&level) {
135            return Err(serde::de::Error::custom(format!(
136                "level {level} is not in {}..={}",
137                level_range.start(),
138                level_range.end()
139            )));
140        }
141
142        Ok(Self { level })
143    }
144}
145
146#[derive(Debug, Error)]
147/// Errors that may occur when applying the [`ZstdCodec`].
148pub enum ZstdCodecError {
149    /// [`ZstdCodec`] failed to encode the header
150    #[error("Zstd failed to encode the header")]
151    HeaderEncodeFailed {
152        /// Opaque source error
153        source: ZstdHeaderError,
154    },
155    /// [`ZstdCodec`] failed to encode the encoded data
156    #[error("Zstd failed to decode the encoded data")]
157    ZstdEncodeFailed {
158        /// Opaque source error
159        source: ZstdCodingError,
160    },
161    /// [`ZstdCodec`] can only decode one-dimensional byte arrays but received
162    /// an array of a different dtype
163    #[error(
164        "Zstd can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
165    )]
166    EncodedDataNotBytes {
167        /// The unexpected dtype of the encoded array
168        dtype: AnyArrayDType,
169    },
170    /// [`ZstdCodec`] can only decode one-dimensional byte arrays but received
171    /// an array of a different shape
172    #[error(
173        "Zstd can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
174    )]
175    EncodedDataNotOneDimensional {
176        /// The unexpected shape of the encoded array
177        shape: Vec<usize>,
178    },
179    /// [`ZstdCodec`] failed to encode the header
180    #[error("Zstd failed to decode the header")]
181    HeaderDecodeFailed {
182        /// Opaque source error
183        source: ZstdHeaderError,
184    },
185    /// [`ZstdCodec`] decode consumed less encoded data, which contains trailing
186    /// junk
187    #[error("Zstd decode consumed less encoded data, which contains trailing junk")]
188    DecodeExcessiveEncodedData,
189    /// [`ZstdCodec`] produced less decoded data than expected
190    #[error("Zstd produced less decoded data than expected")]
191    DecodeProducedLess,
192    /// [`ZstdCodec`] failed to decode the encoded data
193    #[error("Zstd failed to decode the encoded data")]
194    ZstdDecodeFailed {
195        /// Opaque source error
196        source: ZstdCodingError,
197    },
198    /// [`ZstdCodec`] cannot decode into the provided array
199    #[error("Zstd cannot decode into the provided array")]
200    MismatchedDecodeIntoArray {
201        /// The source of the error
202        #[from]
203        source: AnyArrayAssignError,
204    },
205}
206
207#[derive(Debug, Error)]
208#[error(transparent)]
209/// Opaque error for when encoding or decoding the header fails
210pub struct ZstdHeaderError(postcard::Error);
211
212#[derive(Debug, Error)]
213#[error(transparent)]
214/// Opaque error for when encoding or decoding with Zstandard fails
215pub struct ZstdCodingError(io::Error);
216
217#[expect(clippy::needless_pass_by_value)]
218/// Compress the `array` using Zstandard with the provided `level`.
219///
220/// # Errors
221///
222/// Errors with
223/// - [`ZstdCodecError::HeaderEncodeFailed`] if encoding the header to the
224///   output bytevec failed
225/// - [`ZstdCodecError::ZstdEncodeFailed`] if an opaque encoding error occurred
226///
227/// # Panics
228///
229/// Panics if the infallible encoding with Zstd fails.
230pub fn compress(array: AnyArrayView, level: ZstdLevel) -> Result<Vec<u8>, ZstdCodecError> {
231    let mut encoded = postcard::to_extend(
232        &CompressionHeader {
233            dtype: array.dtype(),
234            shape: Cow::Borrowed(array.shape()),
235            version: StaticCodecVersion,
236        },
237        Vec::new(),
238    )
239    .map_err(|err| ZstdCodecError::HeaderEncodeFailed {
240        source: ZstdHeaderError(err),
241    })?;
242
243    zstd::stream::copy_encode(&*array.as_bytes(), &mut encoded, level.level).map_err(|err| {
244        ZstdCodecError::ZstdEncodeFailed {
245            source: ZstdCodingError(err),
246        }
247    })?;
248
249    Ok(encoded)
250}
251
252/// Decompress the `encoded` data into an array using Zstandard.
253///
254/// # Errors
255///
256/// Errors with
257/// - [`ZstdCodecError::HeaderDecodeFailed`] if decoding the header failed
258/// - [`ZstdCodecError::DecodeExcessiveEncodedData`] if the encoded data
259///   contains excessive trailing data junk
260/// - [`ZstdCodecError::DecodeProducedLess`] if decoding produced less data than
261///   expected
262/// - [`ZstdCodecError::ZstdDecodeFailed`] if an opaque decoding error occurred
263pub fn decompress(encoded: &[u8]) -> Result<AnyArray, ZstdCodecError> {
264    let (header, encoded) =
265        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
266            ZstdCodecError::HeaderDecodeFailed {
267                source: ZstdHeaderError(err),
268            }
269        })?;
270
271    let (decoded, result) = AnyArray::with_zeros_bytes(header.dtype, &header.shape, |decoded| {
272        decompress_into_bytes(encoded, decoded)
273    });
274
275    result.map(|()| decoded)
276}
277
278/// Decompress the `encoded` data into a `decoded` array using Zstandard.
279///
280/// # Errors
281///
282/// Errors with
283/// - [`ZstdCodecError::HeaderDecodeFailed`] if decoding the header failed
284/// - [`ZstdCodecError::MismatchedDecodeIntoArray`] if the `decoded` array is of
285///   the wrong dtype or shape
286/// - [`ZstdCodecError::HeaderDecodeFailed`] if decoding the header failed
287/// - [`ZstdCodecError::DecodeExcessiveEncodedData`] if the encoded data
288///   contains excessive trailing data junk
289/// - [`ZstdCodecError::DecodeProducedLess`] if decoding produced less data than
290///   expected
291/// - [`ZstdCodecError::ZstdDecodeFailed`] if an opaque decoding error occurred
292pub fn decompress_into(encoded: &[u8], mut decoded: AnyArrayViewMut) -> Result<(), ZstdCodecError> {
293    let (header, encoded) =
294        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
295            ZstdCodecError::HeaderDecodeFailed {
296                source: ZstdHeaderError(err),
297            }
298        })?;
299
300    if header.dtype != decoded.dtype() {
301        return Err(ZstdCodecError::MismatchedDecodeIntoArray {
302            source: AnyArrayAssignError::DTypeMismatch {
303                src: header.dtype,
304                dst: decoded.dtype(),
305            },
306        });
307    }
308
309    if header.shape != decoded.shape() {
310        return Err(ZstdCodecError::MismatchedDecodeIntoArray {
311            source: AnyArrayAssignError::ShapeMismatch {
312                src: header.shape.into_owned(),
313                dst: decoded.shape().to_vec(),
314            },
315        });
316    }
317
318    decoded.with_bytes_mut(|decoded| decompress_into_bytes(encoded, decoded))
319}
320
321fn decompress_into_bytes(mut encoded: &[u8], mut decoded: &mut [u8]) -> Result<(), ZstdCodecError> {
322    // we want to check encoded and decoded for full consumption after the decoding
323    zstd::stream::copy_decode(&mut encoded, &mut decoded).map_err(|err| {
324        ZstdCodecError::ZstdDecodeFailed {
325            source: ZstdCodingError(err),
326        }
327    })?;
328
329    if !encoded.is_empty() {
330        return Err(ZstdCodecError::DecodeExcessiveEncodedData);
331    }
332
333    if !decoded.is_empty() {
334        return Err(ZstdCodecError::DecodeProducedLess);
335    }
336
337    Ok(())
338}
339
340#[derive(Serialize, Deserialize)]
341struct CompressionHeader<'a> {
342    dtype: AnyArrayDType,
343    #[serde(borrow)]
344    shape: Cow<'a, [usize]>,
345    version: ZstdCodecVersion,
346}