Skip to main content

numcodecs_lc/
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-lc
10//! [crates.io]: https://crates.io/crates/numcodecs-lc
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-lc
13//! [docs.rs]: https://docs.rs/numcodecs-lc/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_lc
17//!
18//! LC 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, Deserializer, Serialize};
31use serde_repr::{Deserialize_repr, Serialize_repr};
32use thiserror::Error;
33
34#[cfg(test)]
35use ::serde_json as _;
36
37type LcCodecVersion = StaticCodecVersion<0, 1, 0>;
38
39#[derive(Clone, Serialize, Deserialize, JsonSchema)]
40#[serde(deny_unknown_fields)]
41/// Codec providing compression using LC
42pub struct LcCodec {
43    /// LC preprocessors
44    #[serde(default)]
45    pub preprocessors: Vec<LcPreprocessor>,
46    /// LC components
47    #[serde(deserialize_with = "deserialize_components")]
48    #[schemars(length(min = 1, max = lc_framework::MAX_COMPONENTS))]
49    pub components: Vec<LcComponent>,
50    /// The codec's encoding format version. Do not provide this parameter explicitly.
51    #[serde(default, rename = "_version")]
52    pub version: LcCodecVersion,
53}
54
55fn deserialize_components<'de, D: Deserializer<'de>>(
56    deserializer: D,
57) -> Result<Vec<LcComponent>, D::Error> {
58    let components = Vec::<LcComponent>::deserialize(deserializer)?;
59
60    if components.is_empty() {
61        return Err(serde::de::Error::custom("expected at least one component"));
62    }
63
64    if components.len() > lc_framework::MAX_COMPONENTS {
65        return Err(serde::de::Error::custom(format_args!(
66            "expected at most {} components",
67            lc_framework::MAX_COMPONENTS
68        )));
69    }
70
71    Ok(components)
72}
73
74#[expect(missing_docs)]
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
76#[serde(deny_unknown_fields)]
77#[serde(tag = "id")]
78#[schemars(inline)]
79/// LC preprocessor
80pub enum LcPreprocessor {
81    #[serde(rename = "NUL")]
82    Noop,
83    #[serde(rename = "LOR")]
84    Lorenzo1D { dtype: LcLorenzoDtype },
85    #[serde(rename = "QUANT")]
86    QuantizeErrorBound {
87        dtype: LcQuantizeDType,
88        kind: LcErrorKind,
89        error_bound: f64,
90        threshold: Option<f64>,
91        decorrelation: LcDecorrelation,
92    },
93}
94
95impl LcPreprocessor {
96    const fn into_lc(self) -> lc_framework::Preprocessor {
97        match self {
98            Self::Noop => lc_framework::Preprocessor::Noop,
99            Self::Lorenzo1D { dtype } => lc_framework::Preprocessor::Lorenzo1D {
100                dtype: dtype.into_lc(),
101            },
102            Self::QuantizeErrorBound {
103                dtype,
104                kind,
105                error_bound,
106                threshold,
107                decorrelation,
108            } => lc_framework::Preprocessor::QuantizeErrorBound {
109                dtype: dtype.into_lc(),
110                kind: kind.into_lc(),
111                error_bound,
112                threshold,
113                decorrelation: decorrelation.into_lc(),
114            },
115        }
116    }
117}
118
119#[derive(
120    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
121)]
122#[schemars(inline)]
123/// LC error bound kind
124pub enum LcErrorKind {
125    /// pointwise absolute error bound
126    #[serde(rename = "ABS")]
127    Abs,
128    /// pointwise normalised absolute / data-range-relative error bound
129    #[serde(rename = "NOA")]
130    Noa,
131    /// pointwise relative error bound
132    #[serde(rename = "REL")]
133    Rel,
134}
135
136impl LcErrorKind {
137    const fn into_lc(self) -> lc_framework::ErrorKind {
138        match self {
139            Self::Abs => lc_framework::ErrorKind::Abs,
140            Self::Noa => lc_framework::ErrorKind::Noa,
141            Self::Rel => lc_framework::ErrorKind::Rel,
142        }
143    }
144}
145
146#[expect(missing_docs)]
147#[derive(
148    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
149)]
150#[schemars(inline)]
151/// LC quantisation decorrelation mode
152pub enum LcDecorrelation {
153    #[serde(rename = "0")]
154    Zero,
155    #[serde(rename = "R")]
156    Random,
157}
158
159impl LcDecorrelation {
160    const fn into_lc(self) -> lc_framework::Decorrelation {
161        match self {
162            Self::Zero => lc_framework::Decorrelation::Zero,
163            Self::Random => lc_framework::Decorrelation::Random,
164        }
165    }
166}
167
168#[expect(missing_docs)]
169#[derive(
170    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
171)]
172#[schemars(inline)]
173/// LC Lorenzo preprocessor dtype
174pub enum LcLorenzoDtype {
175    #[serde(rename = "i32")]
176    I32,
177}
178
179impl LcLorenzoDtype {
180    const fn into_lc(self) -> lc_framework::LorenzoDtype {
181        match self {
182            Self::I32 => lc_framework::LorenzoDtype::I32,
183        }
184    }
185}
186
187#[expect(missing_docs)]
188#[derive(
189    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
190)]
191#[schemars(inline)]
192/// LC quantization dtype
193pub enum LcQuantizeDType {
194    #[serde(rename = "f32")]
195    F32,
196    #[serde(rename = "f64")]
197    F64,
198}
199
200impl LcQuantizeDType {
201    const fn into_lc(self) -> lc_framework::QuantizeDType {
202        match self {
203            Self::F32 => lc_framework::QuantizeDType::F32,
204            Self::F64 => lc_framework::QuantizeDType::F64,
205        }
206    }
207}
208
209#[expect(missing_docs)]
210#[derive(
211    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
212)]
213#[serde(deny_unknown_fields)]
214#[serde(tag = "id")]
215#[schemars(inline)]
216/// LC component
217pub enum LcComponent {
218    #[serde(rename = "NUL")]
219    Noop,
220    // mutators
221    #[serde(rename = "TCMS")]
222    TwosComplementToSignMagnitude { size: LcElemSize },
223    #[serde(rename = "TCNB")]
224    TwosComplementToNegaBinary { size: LcElemSize },
225    #[serde(rename = "DBEFS")]
226    DebiasedExponentFractionSign { size: LcFloatSize },
227    #[serde(rename = "DBESF")]
228    DebiasedExponentSignFraction { size: LcFloatSize },
229    // shufflers
230    #[serde(rename = "BIT")]
231    BitShuffle { size: LcElemSize },
232    #[serde(rename = "TUPL")]
233    Tuple { size: LcTupleSize },
234    // predictors
235    #[serde(rename = "DIFF")]
236    Delta { size: LcElemSize },
237    #[serde(rename = "DIFFMS")]
238    DeltaAsSignMagnitude { size: LcElemSize },
239    #[serde(rename = "DIFFNB")]
240    DeltaAsNegaBinary { size: LcElemSize },
241    // reducers
242    #[serde(rename = "CLOG")]
243    Clog { size: LcElemSize },
244    #[serde(rename = "HCLOG")]
245    HClog { size: LcElemSize },
246    #[serde(rename = "RARE")]
247    Rare { size: LcElemSize },
248    #[serde(rename = "RAZE")]
249    Raze { size: LcElemSize },
250    #[serde(rename = "RLE")]
251    RunLengthEncoding { size: LcElemSize },
252    #[serde(rename = "RRE")]
253    RepetitionRunBitmapEncoding { size: LcElemSize },
254    #[serde(rename = "RZE")]
255    ZeroRunBitmapEncoding { size: LcElemSize },
256}
257
258impl LcComponent {
259    const fn into_lc(self) -> lc_framework::Component {
260        match self {
261            Self::Noop => lc_framework::Component::Noop,
262            // mutators
263            Self::TwosComplementToSignMagnitude { size } => {
264                lc_framework::Component::TwosComplementToSignMagnitude {
265                    size: size.into_lc(),
266                }
267            }
268            Self::TwosComplementToNegaBinary { size } => {
269                lc_framework::Component::TwosComplementToNegaBinary {
270                    size: size.into_lc(),
271                }
272            }
273            Self::DebiasedExponentFractionSign { size } => {
274                lc_framework::Component::DebiasedExponentFractionSign {
275                    size: size.into_lc(),
276                }
277            }
278            Self::DebiasedExponentSignFraction { size } => {
279                lc_framework::Component::DebiasedExponentSignFraction {
280                    size: size.into_lc(),
281                }
282            }
283            // shufflers
284            Self::BitShuffle { size } => lc_framework::Component::BitShuffle {
285                size: size.into_lc(),
286            },
287            Self::Tuple { size } => lc_framework::Component::Tuple {
288                size: size.into_lc(),
289            },
290            // predictors
291            Self::Delta { size } => lc_framework::Component::Delta {
292                size: size.into_lc(),
293            },
294            Self::DeltaAsSignMagnitude { size } => lc_framework::Component::DeltaAsSignMagnitude {
295                size: size.into_lc(),
296            },
297            Self::DeltaAsNegaBinary { size } => lc_framework::Component::DeltaAsNegaBinary {
298                size: size.into_lc(),
299            },
300            // reducers
301            Self::Clog { size } => lc_framework::Component::Clog {
302                size: size.into_lc(),
303            },
304            Self::HClog { size } => lc_framework::Component::HClog {
305                size: size.into_lc(),
306            },
307            Self::Rare { size } => lc_framework::Component::Rare {
308                size: size.into_lc(),
309            },
310            Self::Raze { size } => lc_framework::Component::Raze {
311                size: size.into_lc(),
312            },
313            Self::RunLengthEncoding { size } => lc_framework::Component::RunLengthEncoding {
314                size: size.into_lc(),
315            },
316            Self::RepetitionRunBitmapEncoding { size } => {
317                lc_framework::Component::RepetitionRunBitmapEncoding {
318                    size: size.into_lc(),
319                }
320            }
321            Self::ZeroRunBitmapEncoding { size } => {
322                lc_framework::Component::ZeroRunBitmapEncoding {
323                    size: size.into_lc(),
324                }
325            }
326        }
327    }
328}
329
330#[expect(missing_docs)]
331#[derive(
332    Copy,
333    Clone,
334    Debug,
335    PartialEq,
336    Eq,
337    PartialOrd,
338    Ord,
339    Hash,
340    Serialize_repr,
341    Deserialize_repr,
342    JsonSchema_repr,
343)]
344/// LC component element size, in bytes
345#[repr(u8)]
346pub enum LcElemSize {
347    S1 = 1,
348    S2 = 2,
349    S4 = 4,
350    S8 = 8,
351}
352
353impl LcElemSize {
354    const fn into_lc(self) -> lc_framework::ElemSize {
355        match self {
356            Self::S1 => lc_framework::ElemSize::S1,
357            Self::S2 => lc_framework::ElemSize::S2,
358            Self::S4 => lc_framework::ElemSize::S4,
359            Self::S8 => lc_framework::ElemSize::S8,
360        }
361    }
362}
363
364#[expect(missing_docs)]
365#[derive(
366    Copy,
367    Clone,
368    Debug,
369    PartialEq,
370    Eq,
371    PartialOrd,
372    Ord,
373    Hash,
374    Serialize_repr,
375    Deserialize_repr,
376    JsonSchema_repr,
377)]
378/// LC component float element size, in bytes
379#[repr(u8)]
380pub enum LcFloatSize {
381    S4 = 4,
382    S8 = 8,
383}
384
385impl LcFloatSize {
386    const fn into_lc(self) -> lc_framework::FloatSize {
387        match self {
388            Self::S4 => lc_framework::FloatSize::S4,
389            Self::S8 => lc_framework::FloatSize::S8,
390        }
391    }
392}
393
394#[expect(missing_docs)]
395#[derive(
396    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
397)]
398/// LC tuple component element size, in bytes x tuple length
399#[schemars(description = "LC tuple component element size, in tuple length _ bytes")]
400pub enum LcTupleSize {
401    #[serde(rename = "2_1")]
402    S1x2,
403    #[serde(rename = "3_1")]
404    S1x3,
405    #[serde(rename = "4_1")]
406    S1x4,
407    #[serde(rename = "6_1")]
408    S1x6,
409    #[serde(rename = "8_1")]
410    S1x8,
411    #[serde(rename = "12_1")]
412    S1x12,
413    #[serde(rename = "2_2")]
414    S2x2,
415    #[serde(rename = "3_2")]
416    S2x3,
417    #[serde(rename = "4_2")]
418    S2x4,
419    #[serde(rename = "6_2")]
420    S2x6,
421    #[serde(rename = "2_4")]
422    S4x2,
423    #[serde(rename = "6_4")]
424    S4x6,
425    #[serde(rename = "3_8")]
426    S8x3,
427    #[serde(rename = "6_8")]
428    S8x6,
429}
430
431impl LcTupleSize {
432    const fn into_lc(self) -> lc_framework::TupleSize {
433        match self {
434            Self::S1x2 => lc_framework::TupleSize::S1x2,
435            Self::S1x3 => lc_framework::TupleSize::S1x3,
436            Self::S1x4 => lc_framework::TupleSize::S1x4,
437            Self::S1x6 => lc_framework::TupleSize::S1x6,
438            Self::S1x8 => lc_framework::TupleSize::S1x8,
439            Self::S1x12 => lc_framework::TupleSize::S1x12,
440            Self::S2x2 => lc_framework::TupleSize::S2x2,
441            Self::S2x3 => lc_framework::TupleSize::S2x3,
442            Self::S2x4 => lc_framework::TupleSize::S2x4,
443            Self::S2x6 => lc_framework::TupleSize::S2x6,
444            Self::S4x2 => lc_framework::TupleSize::S4x2,
445            Self::S4x6 => lc_framework::TupleSize::S4x6,
446            Self::S8x3 => lc_framework::TupleSize::S8x3,
447            Self::S8x6 => lc_framework::TupleSize::S8x6,
448        }
449    }
450}
451
452impl Codec for LcCodec {
453    type Error = LcCodecError;
454
455    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
456        compress(data.view(), &self.preprocessors, &self.components)
457            .map(|bytes| AnyArray::U8(Array1::from_vec(bytes).into_dyn()))
458    }
459
460    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
461        let AnyCowArray::U8(encoded) = encoded else {
462            return Err(LcCodecError::EncodedDataNotBytes {
463                dtype: encoded.dtype(),
464            });
465        };
466
467        if !matches!(encoded.shape(), [_]) {
468            return Err(LcCodecError::EncodedDataNotOneDimensional {
469                shape: encoded.shape().to_vec(),
470            });
471        }
472
473        decompress(
474            &self.preprocessors,
475            &self.components,
476            &AnyCowArray::U8(encoded).as_bytes(),
477        )
478    }
479
480    fn decode_into(
481        &self,
482        encoded: AnyArrayView,
483        decoded: AnyArrayViewMut,
484    ) -> Result<(), Self::Error> {
485        let AnyArrayView::U8(encoded) = encoded else {
486            return Err(LcCodecError::EncodedDataNotBytes {
487                dtype: encoded.dtype(),
488            });
489        };
490
491        if !matches!(encoded.shape(), [_]) {
492            return Err(LcCodecError::EncodedDataNotOneDimensional {
493                shape: encoded.shape().to_vec(),
494            });
495        }
496
497        decompress_into(
498            &self.preprocessors,
499            &self.components,
500            &AnyArrayView::U8(encoded).as_bytes(),
501            decoded,
502        )
503    }
504}
505
506impl StaticCodec for LcCodec {
507    const CODEC_ID: &'static str = "lc.rs";
508
509    type Config<'de> = Self;
510
511    fn from_config(config: Self::Config<'_>) -> Self {
512        config
513    }
514
515    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
516        StaticCodecConfig::from(self)
517    }
518}
519
520#[derive(Debug, Error)]
521/// Errors that may occur when applying the [`LcCodec`].
522pub enum LcCodecError {
523    /// [`LcCodec`] failed to encode the header
524    #[error("Lc failed to encode the header")]
525    HeaderEncodeFailed {
526        /// Opaque source error
527        source: LcHeaderError,
528    },
529    /// [`LcCodec`] failed to encode the encoded data
530    #[error("Lc failed to decode the encoded data")]
531    LcEncodeFailed {
532        /// Opaque source error
533        source: LcCodingError,
534    },
535    /// [`LcCodec`] can only decode one-dimensional byte arrays but received
536    /// an array of a different dtype
537    #[error(
538        "Lc can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
539    )]
540    EncodedDataNotBytes {
541        /// The unexpected dtype of the encoded array
542        dtype: AnyArrayDType,
543    },
544    /// [`LcCodec`] can only decode one-dimensional byte arrays but received
545    /// an array of a different shape
546    #[error(
547        "Lc can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
548    )]
549    EncodedDataNotOneDimensional {
550        /// The unexpected shape of the encoded array
551        shape: Vec<usize>,
552    },
553    /// [`LcCodec`] failed to encode the header
554    #[error("Lc failed to decode the header")]
555    HeaderDecodeFailed {
556        /// Opaque source error
557        source: LcHeaderError,
558    },
559    /// [`LcCodec`] decode produced a different number of bytes than expected
560    #[error("Lc decode produced a different number of bytes than expected")]
561    DecodeDataLengthMismatch,
562    /// [`LcCodec`] failed to decode the encoded data
563    #[error("Lc failed to decode the encoded data")]
564    LcDecodeFailed {
565        /// Opaque source error
566        source: LcCodingError,
567    },
568    /// [`LcCodec`] cannot decode into the provided array
569    #[error("Lc cannot decode into the provided array")]
570    MismatchedDecodeIntoArray {
571        /// The source of the error
572        #[from]
573        source: AnyArrayAssignError,
574    },
575}
576
577#[derive(Debug, Error)]
578#[error(transparent)]
579/// Opaque error for when encoding or decoding the header fails
580pub struct LcHeaderError(postcard::Error);
581
582#[derive(Debug, Error)]
583#[error(transparent)]
584/// Opaque error for when encoding or decoding with LC fails
585pub struct LcCodingError(lc_framework::Error);
586
587#[expect(clippy::needless_pass_by_value)]
588/// Compress the `array` using LC with the provided `preprocessors` and
589/// `components`.
590///
591/// # Errors
592///
593/// Errors with
594/// - [`LcCodecError::HeaderEncodeFailed`] if encoding the header to the
595///   output bytevec failed
596/// - [`LcCodecError::LcEncodeFailed`] if an opaque encoding error occurred
597pub fn compress(
598    array: AnyArrayView,
599    preprocessors: &[LcPreprocessor],
600    components: &[LcComponent],
601) -> Result<Vec<u8>, LcCodecError> {
602    let mut encoded = postcard::to_extend(
603        &CompressionHeader {
604            dtype: array.dtype(),
605            shape: Cow::Borrowed(array.shape()),
606            version: StaticCodecVersion,
607        },
608        Vec::new(),
609    )
610    .map_err(|err| LcCodecError::HeaderEncodeFailed {
611        source: LcHeaderError(err),
612    })?;
613
614    // LC does not support empty input, so skip encoding
615    if array.is_empty() {
616        return Ok(encoded);
617    }
618
619    let preprocessors = preprocessors
620        .iter()
621        .cloned()
622        .map(LcPreprocessor::into_lc)
623        .collect::<Vec<_>>();
624    let components = components
625        .iter()
626        .copied()
627        .map(LcComponent::into_lc)
628        .collect::<Vec<_>>();
629
630    encoded.append(
631        &mut lc_framework::compress(&preprocessors, &components, &array.as_bytes()).map_err(
632            |err| LcCodecError::LcEncodeFailed {
633                source: LcCodingError(err),
634            },
635        )?,
636    );
637
638    Ok(encoded)
639}
640
641/// Decompress the `encoded` data into an array using LC.
642///
643/// # Errors
644///
645/// Errors with
646/// - [`LcCodecError::HeaderDecodeFailed`] if decoding the header failed
647/// - [`LcCodecError::DecodeDataLengthMismatch`] if decoding produced a
648///   different number of bytes than expected
649/// - [`LcCodecError::LcDecodeFailed`] if an opaque decoding error occurred
650pub fn decompress(
651    preprocessors: &[LcPreprocessor],
652    components: &[LcComponent],
653    encoded: &[u8],
654) -> Result<AnyArray, LcCodecError> {
655    let (header, encoded) =
656        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
657            LcCodecError::HeaderDecodeFailed {
658                source: LcHeaderError(err),
659            }
660        })?;
661
662    let (decoded, result) = AnyArray::with_zeros_bytes(header.dtype, &header.shape, |decoded| {
663        decompress_into_bytes(preprocessors, components, encoded, decoded)
664    });
665
666    result.map(|()| decoded)
667}
668
669/// Decompress the `encoded` data into a `decoded` array using LC.
670///
671/// # Errors
672///
673/// Errors with
674/// - [`LcCodecError::HeaderDecodeFailed`] if decoding the header failed
675/// - [`LcCodecError::MismatchedDecodeIntoArray`] if the `decoded` array is of
676///   the wrong dtype or shape
677/// - [`LcCodecError::HeaderDecodeFailed`] if decoding the header failed
678/// - [`LcCodecError::DecodeDataLengthMismatch`] if decoding produced a
679///   different number of bytes than expected
680/// - [`LcCodecError::LcDecodeFailed`] if an opaque decoding error occurred
681pub fn decompress_into(
682    preprocessors: &[LcPreprocessor],
683    components: &[LcComponent],
684    encoded: &[u8],
685    mut decoded: AnyArrayViewMut,
686) -> Result<(), LcCodecError> {
687    let (header, encoded) =
688        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
689            LcCodecError::HeaderDecodeFailed {
690                source: LcHeaderError(err),
691            }
692        })?;
693
694    if header.dtype != decoded.dtype() {
695        return Err(LcCodecError::MismatchedDecodeIntoArray {
696            source: AnyArrayAssignError::DTypeMismatch {
697                src: header.dtype,
698                dst: decoded.dtype(),
699            },
700        });
701    }
702
703    if header.shape != decoded.shape() {
704        return Err(LcCodecError::MismatchedDecodeIntoArray {
705            source: AnyArrayAssignError::ShapeMismatch {
706                src: header.shape.into_owned(),
707                dst: decoded.shape().to_vec(),
708            },
709        });
710    }
711
712    decoded.with_bytes_mut(|decoded| {
713        decompress_into_bytes(preprocessors, components, encoded, decoded)
714    })
715}
716
717fn decompress_into_bytes(
718    preprocessors: &[LcPreprocessor],
719    components: &[LcComponent],
720    encoded: &[u8],
721    decoded: &mut [u8],
722) -> Result<(), LcCodecError> {
723    // LC does not support empty input, so skip decoding
724    if decoded.is_empty() && encoded.is_empty() {
725        return Ok(());
726    }
727
728    let preprocessors = preprocessors
729        .iter()
730        .cloned()
731        .map(LcPreprocessor::into_lc)
732        .collect::<Vec<_>>();
733    let components = components
734        .iter()
735        .copied()
736        .map(LcComponent::into_lc)
737        .collect::<Vec<_>>();
738
739    let dec = lc_framework::decompress(&preprocessors, &components, encoded).map_err(|err| {
740        LcCodecError::LcDecodeFailed {
741            source: LcCodingError(err),
742        }
743    })?;
744
745    if dec.len() != decoded.len() {
746        return Err(LcCodecError::DecodeDataLengthMismatch);
747    }
748
749    decoded.copy_from_slice(&dec);
750
751    Ok(())
752}
753
754#[derive(Serialize, Deserialize)]
755struct CompressionHeader<'a> {
756    dtype: AnyArrayDType,
757    #[serde(borrow)]
758    shape: Cow<'a, [usize]>,
759    version: LcCodecVersion,
760}
761
762#[cfg(test)]
763#[expect(clippy::unwrap_used, clippy::panic)]
764mod tests {
765    use super::*;
766
767    #[test]
768    fn lossless() {
769        let data = ndarray::linspace(0.0, std::f32::consts::PI, 100)
770            .collect::<Array1<f32>>()
771            .into_shape_with_order((10, 10))
772            .unwrap()
773            .cos();
774
775        let preprocessors = &[];
776        let components = &[
777            LcComponent::BitShuffle {
778                size: LcElemSize::S4,
779            },
780            LcComponent::RunLengthEncoding {
781                size: LcElemSize::S4,
782            },
783        ];
784
785        let compressed = compress(
786            AnyArrayView::F32(data.view().into_dyn()),
787            preprocessors,
788            components,
789        )
790        .unwrap();
791        let decompressed = decompress(preprocessors, components, &compressed).unwrap();
792
793        assert_eq!(decompressed, AnyArray::F32(data.into_dyn()));
794    }
795
796    #[test]
797    fn abs_error() {
798        let data = ndarray::linspace(0.0, std::f32::consts::PI, 100)
799            .collect::<Array1<f32>>()
800            .into_shape_with_order((10, 10))
801            .unwrap()
802            .cos();
803
804        let preprocessors = &[LcPreprocessor::QuantizeErrorBound {
805            dtype: LcQuantizeDType::F32,
806            kind: LcErrorKind::Abs,
807            error_bound: 0.1,
808            threshold: None,
809            decorrelation: LcDecorrelation::Zero,
810        }];
811        let components = &[
812            LcComponent::BitShuffle {
813                size: LcElemSize::S4,
814            },
815            LcComponent::RunLengthEncoding {
816                size: LcElemSize::S4,
817            },
818        ];
819
820        let compressed = compress(
821            AnyArrayView::F32(data.view().into_dyn()),
822            preprocessors,
823            components,
824        )
825        .unwrap();
826        let decompressed = decompress(preprocessors, components, &compressed).unwrap();
827
828        let AnyArray::F32(decompressed) = decompressed else {
829            panic!("unexpected decompressed dtype {}", decompressed.dtype());
830        };
831        assert_eq!(decompressed.shape(), data.shape());
832
833        for (o, d) in data.into_iter().zip(decompressed) {
834            assert!((o - d).abs() <= 0.1);
835        }
836    }
837}