Skip to main content

numcodecs_pco/
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-pco
10//! [crates.io]: https://crates.io/crates/numcodecs-pco
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-pco
13//! [docs.rs]: https://docs.rs/numcodecs-pco/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_pco
17//!
18//! Pcodec implementation for the [`numcodecs`] API.
19
20#![allow(clippy::multiple_crate_versions)] // embedded-io
21
22use std::{borrow::Cow, fmt, num::NonZeroUsize};
23
24use ndarray::{Array, Array1, ArrayBase, ArrayViewMut, Data, Dimension, ShapeError};
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 PcodecVersion = StaticCodecVersion<0, 2, 0>;
38
39#[derive(Clone, Serialize, Deserialize, JsonSchema)]
40#[schemars(deny_unknown_fields)] // serde cannot deny unknown fields because of the flatten
41/// Codec providing compression using pco
42pub struct Pcodec {
43    /// Compression level, ranging from 0 (weak) over 8 (very good) to 12
44    /// (expensive)
45    pub level: PcoCompressionLevel,
46    /// Specifies how the mode should be determined
47    #[serde(flatten)]
48    pub mode: PcoModeSpec,
49    /// Specifies how delta encoding should be chosen
50    #[serde(flatten)]
51    pub delta: PcoDeltaSpec,
52    /// Specifies how the chunk should be split into pages
53    #[serde(flatten)]
54    pub paging: PcoPagingSpec,
55    /// The codec's encoding format version. Do not provide this parameter explicitly.
56    #[serde(default, rename = "_version")]
57    pub version: PcodecVersion,
58}
59
60#[derive(
61    Copy, Clone, Debug, Default, PartialEq, Eq, Serialize_repr, Deserialize_repr, JsonSchema_repr,
62)]
63#[repr(u8)]
64#[schemars(inline)]
65/// Pco compression level.
66///
67/// The level ranges from 0 to 12 inclusive (default: 8):
68/// * Level 0 achieves only a small amount of compression.
69/// * Level 8 achieves very good compression.
70/// * Level 12 achieves marginally better compression than 8.
71#[expect(missing_docs)]
72pub enum PcoCompressionLevel {
73    Level0 = 0,
74    Level1 = 1,
75    Level2 = 2,
76    Level3 = 3,
77    Level4 = 4,
78    Level5 = 5,
79    Level6 = 6,
80    Level7 = 7,
81    #[default]
82    Level8 = 8,
83    Level9 = 9,
84    Level10 = 10,
85    Level11 = 11,
86    Level12 = 12,
87}
88
89#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
90#[schemars(deny_unknown_fields)] // serde cannot deny unknown fields because of the flatten
91#[serde(tag = "mode", rename_all = "kebab-case")]
92/// Pco compression mode
93pub enum PcoModeSpec {
94    #[default]
95    /// Automatically detects a good mode.
96    ///
97    /// This works well most of the time, but costs some compression time and
98    /// can select a bad mode in adversarial cases.
99    Auto,
100    /// Only uses the classic mode
101    Classic,
102    /// Tries using the `FloatMult` mode with a given base.
103    ///
104    /// Only applies to floating-point types.
105    TryFloatMult {
106        /// the base for the `FloatMult` mode
107        float_mult_base: f64,
108    },
109    /// Tries using the `FloatQuant` mode with the given number of bits of
110    /// quantization.
111    ///
112    /// Only applies to floating-point types.
113    TryFloatQuant {
114        /// the number of bits to which floating-point values are quantized
115        float_quant_bits: u32,
116    },
117    /// Tries using the `IntMult` mode with a given base.
118    ///
119    /// Only applies to integer types.
120    TryIntMult {
121        /// the base for the `IntMult` mode
122        int_mult_base: u64,
123    },
124}
125
126#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
127#[schemars(deny_unknown_fields)] // serde cannot deny unknown fields because of the flatten
128#[serde(tag = "delta", rename_all = "kebab-case")]
129/// Pco delta encoding
130pub enum PcoDeltaSpec {
131    #[default]
132    /// Automatically detects a detects a good delta encoding.
133    ///
134    /// This works well most of the time, but costs some compression time and
135    /// can select a bad delta encoding in adversarial cases.
136    Auto,
137    /// Never uses delta encoding.
138    ///
139    /// This is best if your data is in a random order or adjacent numbers have
140    /// no relation to each other.
141    NoOp,
142    /// Tries taking nth order consecutive deltas.
143    ///
144    /// Supports a delta encoding order up to 7. For instance, 1st order is
145    /// just regular delta encoding, 2nd is deltas-of-deltas, etc. It is legal
146    /// to use 0th order, but it is identical to None.
147    TryConsecutive {
148        /// the order of the delta encoding
149        delta_encoding_order: PcoDeltaEncodingConsecutiveOrder,
150    },
151    /// Tries delta encoding according to an extra latent variable of
152    /// "lookback".
153    ///
154    /// This can improve compression ratio when there are nontrivial patterns
155    /// in the array, but reduces compression speed substantially.
156    TryLookback,
157    /// Tries delta encoding by subtracting a convolution of the previous
158    /// `delta_encoding_order` elements.
159    ///
160    /// This is best if your numbers have local trends that aren't captured by
161    /// simply taking differences, and you are willing to accept noticeably
162    /// reduced decompression speeds.
163    TryConv1 {
164        /// the order of the delta encoding
165        delta_encoding_order: PcoDeltaEncodingConv1Order,
166    },
167}
168
169#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize_repr, Deserialize_repr, JsonSchema_repr)]
170#[repr(u8)]
171#[schemars(inline)]
172/// Pco delta encoding order for consecutive deltas.
173///
174/// The order ranges from 0 to 7 inclusive.
175#[expect(missing_docs)]
176pub enum PcoDeltaEncodingConsecutiveOrder {
177    Order0 = 0,
178    Order1 = 1,
179    Order2 = 2,
180    Order3 = 3,
181    Order4 = 4,
182    Order5 = 5,
183    Order6 = 6,
184    Order7 = 7,
185}
186
187#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize_repr, Deserialize_repr, JsonSchema_repr)]
188#[repr(u8)]
189#[schemars(inline)]
190/// Pco delta encoding order for convolution deltas.
191///
192/// The order ranges from 0 to 32 inclusive.
193#[expect(missing_docs)]
194pub enum PcoDeltaEncodingConv1Order {
195    Order0 = 0,
196    Order1 = 1,
197    Order2 = 2,
198    Order3 = 3,
199    Order4 = 4,
200    Order5 = 5,
201    Order6 = 6,
202    Order7 = 7,
203    Order8 = 8,
204    Order9 = 9,
205    Order10 = 10,
206    Order11 = 11,
207    Order12 = 12,
208    Order13 = 13,
209    Order14 = 14,
210    Order15 = 15,
211    Order16 = 16,
212    Order17 = 17,
213    Order18 = 18,
214    Order19 = 19,
215    Order20 = 20,
216    Order21 = 21,
217    Order22 = 22,
218    Order23 = 23,
219    Order24 = 24,
220    Order25 = 25,
221    Order26 = 26,
222    Order27 = 27,
223    Order28 = 28,
224    Order29 = 29,
225    Order30 = 30,
226    Order31 = 31,
227    Order32 = 32,
228}
229
230#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
231#[schemars(deny_unknown_fields)] // serde cannot deny unknown fields because of the flatten
232#[serde(tag = "paging", rename_all = "kebab-case")]
233/// Pco paging mode
234pub enum PcoPagingSpec {
235    /// Divide the chunk into equal pages of up to this many numbers.
236    ///
237    /// For example, with equal pages up to 100,000, a chunk of 150,000 numbers
238    /// would be divided into 2 pages, each of 75,000 numbers.
239    EqualPagesUpTo {
240        #[serde(default = "default_equal_pages_up_to")]
241        /// maximum amount of numbers in a page
242        equal_pages_up_to: NonZeroUsize,
243    },
244}
245
246impl Default for PcoPagingSpec {
247    fn default() -> Self {
248        Self::EqualPagesUpTo {
249            equal_pages_up_to: default_equal_pages_up_to(),
250        }
251    }
252}
253
254const fn default_equal_pages_up_to() -> NonZeroUsize {
255    NonZeroUsize::MIN.saturating_add(pco::DEFAULT_MAX_PAGE_N.saturating_sub(1))
256}
257
258impl Codec for Pcodec {
259    type Error = PcodecError;
260
261    #[expect(clippy::too_many_lines)] // FIXME
262    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
263        match data {
264            AnyCowArray::U8(data) => Ok(AnyArray::U8(
265                Array1::from(compress(
266                    data,
267                    self.level,
268                    self.mode,
269                    self.delta,
270                    self.paging,
271                )?)
272                .into_dyn(),
273            )),
274            AnyCowArray::U16(data) => Ok(AnyArray::U8(
275                Array1::from(compress(
276                    data,
277                    self.level,
278                    self.mode,
279                    self.delta,
280                    self.paging,
281                )?)
282                .into_dyn(),
283            )),
284            AnyCowArray::U32(data) => Ok(AnyArray::U8(
285                Array1::from(compress(
286                    data,
287                    self.level,
288                    self.mode,
289                    self.delta,
290                    self.paging,
291                )?)
292                .into_dyn(),
293            )),
294            AnyCowArray::U64(data) => Ok(AnyArray::U8(
295                Array1::from(compress(
296                    data,
297                    self.level,
298                    self.mode,
299                    self.delta,
300                    self.paging,
301                )?)
302                .into_dyn(),
303            )),
304            AnyCowArray::I8(data) => Ok(AnyArray::U8(
305                Array1::from(compress(
306                    data,
307                    self.level,
308                    self.mode,
309                    self.delta,
310                    self.paging,
311                )?)
312                .into_dyn(),
313            )),
314            AnyCowArray::I16(data) => Ok(AnyArray::U8(
315                Array1::from(compress(
316                    data,
317                    self.level,
318                    self.mode,
319                    self.delta,
320                    self.paging,
321                )?)
322                .into_dyn(),
323            )),
324            AnyCowArray::I32(data) => Ok(AnyArray::U8(
325                Array1::from(compress(
326                    data,
327                    self.level,
328                    self.mode,
329                    self.delta,
330                    self.paging,
331                )?)
332                .into_dyn(),
333            )),
334            AnyCowArray::I64(data) => Ok(AnyArray::U8(
335                Array1::from(compress(
336                    data,
337                    self.level,
338                    self.mode,
339                    self.delta,
340                    self.paging,
341                )?)
342                .into_dyn(),
343            )),
344            AnyCowArray::F32(data) => Ok(AnyArray::U8(
345                Array1::from(compress(
346                    data,
347                    self.level,
348                    self.mode,
349                    self.delta,
350                    self.paging,
351                )?)
352                .into_dyn(),
353            )),
354            AnyCowArray::F64(data) => Ok(AnyArray::U8(
355                Array1::from(compress(
356                    data,
357                    self.level,
358                    self.mode,
359                    self.delta,
360                    self.paging,
361                )?)
362                .into_dyn(),
363            )),
364            encoded => Err(PcodecError::UnsupportedDtype(encoded.dtype())),
365        }
366    }
367
368    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
369        let AnyCowArray::U8(encoded) = encoded else {
370            return Err(PcodecError::EncodedDataNotBytes {
371                dtype: encoded.dtype(),
372            });
373        };
374
375        if !matches!(encoded.shape(), [_]) {
376            return Err(PcodecError::EncodedDataNotOneDimensional {
377                shape: encoded.shape().to_vec(),
378            });
379        }
380
381        decompress(&AnyCowArray::U8(encoded).as_bytes())
382    }
383
384    fn decode_into(
385        &self,
386        encoded: AnyArrayView,
387        decoded: AnyArrayViewMut,
388    ) -> Result<(), Self::Error> {
389        let AnyArrayView::U8(encoded) = encoded else {
390            return Err(PcodecError::EncodedDataNotBytes {
391                dtype: encoded.dtype(),
392            });
393        };
394
395        if !matches!(encoded.shape(), [_]) {
396            return Err(PcodecError::EncodedDataNotOneDimensional {
397                shape: encoded.shape().to_vec(),
398            });
399        }
400
401        let encoded = AnyArrayView::U8(encoded);
402        let encoded = encoded.as_bytes();
403
404        match decoded {
405            AnyArrayViewMut::U8(decoded) => decompress_into(&encoded, decoded),
406            AnyArrayViewMut::U16(decoded) => decompress_into(&encoded, decoded),
407            AnyArrayViewMut::U32(decoded) => decompress_into(&encoded, decoded),
408            AnyArrayViewMut::U64(decoded) => decompress_into(&encoded, decoded),
409            AnyArrayViewMut::I8(decoded) => decompress_into(&encoded, decoded),
410            AnyArrayViewMut::I16(decoded) => decompress_into(&encoded, decoded),
411            AnyArrayViewMut::I32(decoded) => decompress_into(&encoded, decoded),
412            AnyArrayViewMut::I64(decoded) => decompress_into(&encoded, decoded),
413            AnyArrayViewMut::F32(decoded) => decompress_into(&encoded, decoded),
414            AnyArrayViewMut::F64(decoded) => decompress_into(&encoded, decoded),
415            decoded => Err(PcodecError::UnsupportedDtype(decoded.dtype())),
416        }
417    }
418}
419
420impl StaticCodec for Pcodec {
421    const CODEC_ID: &'static str = "pco.rs";
422
423    type Config<'de> = Self;
424
425    fn from_config(config: Self::Config<'_>) -> Self {
426        config
427    }
428
429    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
430        StaticCodecConfig::from(self)
431    }
432}
433
434#[derive(Debug, Error)]
435/// Errors that may occur when applying the [`Pcodec`].
436pub enum PcodecError {
437    /// [`Pcodec`] does not support the dtype
438    #[error("Pco does not support the dtype {0}")]
439    UnsupportedDtype(AnyArrayDType),
440    /// [`Pcodec`] failed to encode the header
441    #[error("Pco failed to encode the header")]
442    HeaderEncodeFailed {
443        /// Opaque source error
444        source: PcoHeaderError,
445    },
446    /// [`Pcodec`] failed to encode the data
447    #[error("Pco failed to encode the data")]
448    PcoEncodeFailed {
449        /// Opaque source error
450        source: PcoCodingError,
451    },
452    /// [`Pcodec`] can only decode one-dimensional byte arrays but received
453    /// an array of a different dtype
454    #[error(
455        "Pco can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
456    )]
457    EncodedDataNotBytes {
458        /// The unexpected dtype of the encoded array
459        dtype: AnyArrayDType,
460    },
461    /// [`Pcodec`] can only decode one-dimensional byte arrays but received
462    /// an array of a different shape
463    #[error(
464        "Pco can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
465    )]
466    EncodedDataNotOneDimensional {
467        /// The unexpected shape of the encoded array
468        shape: Vec<usize>,
469    },
470    /// [`Pcodec`] failed to decode the header
471    #[error("Pco failed to decode the header")]
472    HeaderDecodeFailed {
473        /// Opaque source error
474        source: PcoHeaderError,
475    },
476    /// [`Pcodec`] failed to decode the data
477    #[error("Pco failed to decode the data")]
478    PcoDecodeFailed {
479        /// Opaque source error
480        source: PcoCodingError,
481    },
482    /// [`Pcodec`] decoded an invalid array shape header which does not fit
483    /// the decoded data
484    #[error("Pco decoded an invalid array shape header which does not fit the decoded data")]
485    DecodeInvalidShapeHeader {
486        /// Source error
487        #[from]
488        source: ShapeError,
489    },
490    /// [`Pcodec`] cannot decode into the provided array
491    #[error("Pco cannot decode into the provided array")]
492    MismatchedDecodeIntoArray {
493        /// The source of the error
494        #[from]
495        source: AnyArrayAssignError,
496    },
497}
498
499#[derive(Debug, Error)]
500#[error(transparent)]
501/// Opaque error for when encoding or decoding the header fails
502pub struct PcoHeaderError(postcard::Error);
503
504#[derive(Debug, Error)]
505#[error(transparent)]
506/// Opaque error for when encoding or decoding with pco fails
507pub struct PcoCodingError(pco::errors::PcoError);
508
509#[expect(clippy::needless_pass_by_value)]
510/// Compresses the input `data` array using pco with the given compression
511/// `level`, `mode`, `delta` encoding, and `paging` mode.
512///
513/// # Errors
514///
515/// Errors with
516/// - [`PcodecError::HeaderEncodeFailed`] if encoding the header failed
517/// - [`PcodecError::PcoEncodeFailed`] if encoding failed with an opaque error
518pub fn compress<T: PcoElement, S: Data<Elem = T>, D: Dimension>(
519    data: ArrayBase<S, D>,
520    level: PcoCompressionLevel,
521    mode: PcoModeSpec,
522    delta: PcoDeltaSpec,
523    paging: PcoPagingSpec,
524) -> Result<Vec<u8>, PcodecError> {
525    let mut encoded_bytes = postcard::to_extend(
526        &CompressionHeader {
527            dtype: <T as PcoElement>::DTYPE,
528            shape: Cow::Borrowed(data.shape()),
529            version: StaticCodecVersion,
530        },
531        Vec::new(),
532    )
533    .map_err(|err| PcodecError::HeaderEncodeFailed {
534        source: PcoHeaderError(err),
535    })?;
536
537    let data_owned;
538    #[expect(clippy::option_if_let_else)]
539    let data = if let Some(slice) = data.as_slice() {
540        slice
541    } else {
542        data_owned = data.into_iter().copied().collect::<Vec<T>>();
543        data_owned.as_slice()
544    };
545
546    let config = pco::ChunkConfig::default()
547        .with_enable_8_bit(true)
548        .with_compression_level(level as usize)
549        .with_mode_spec(match mode {
550            PcoModeSpec::Auto => pco::ModeSpec::Auto,
551            PcoModeSpec::Classic => pco::ModeSpec::Classic,
552            PcoModeSpec::TryFloatMult { float_mult_base } => {
553                pco::ModeSpec::TryFloatMult(float_mult_base)
554            }
555            PcoModeSpec::TryFloatQuant { float_quant_bits } => {
556                pco::ModeSpec::TryFloatQuant(float_quant_bits)
557            }
558            PcoModeSpec::TryIntMult { int_mult_base } => pco::ModeSpec::TryIntMult(int_mult_base),
559        })
560        .with_delta_spec(match delta {
561            PcoDeltaSpec::Auto => pco::DeltaSpec::Auto,
562            PcoDeltaSpec::NoOp => pco::DeltaSpec::NoOp,
563            PcoDeltaSpec::TryConsecutive {
564                delta_encoding_order,
565            } => pco::DeltaSpec::TryConsecutive(delta_encoding_order as usize),
566            PcoDeltaSpec::TryLookback => pco::DeltaSpec::TryLookback,
567            PcoDeltaSpec::TryConv1 {
568                delta_encoding_order,
569            } => pco::DeltaSpec::TryConv1(delta_encoding_order as usize),
570        })
571        .with_paging_spec(match paging {
572            PcoPagingSpec::EqualPagesUpTo { equal_pages_up_to } => {
573                pco::PagingSpec::EqualPagesUpTo(equal_pages_up_to.get())
574            }
575        });
576
577    let encoded = pco::standalone::simple_compress(data, &config).map_err(|err| {
578        PcodecError::PcoEncodeFailed {
579            source: PcoCodingError(err),
580        }
581    })?;
582    encoded_bytes.extend_from_slice(&encoded);
583
584    Ok(encoded_bytes)
585}
586
587/// Decompresses the `encoded` data into an array.
588///
589/// # Errors
590///
591/// Errors with
592/// - [`PcodecError::HeaderDecodeFailed`] if decoding the header failed
593/// - [`PcodecError::PcoDecodeFailed`] if decoding failed with an opaque error
594pub fn decompress(encoded: &[u8]) -> Result<AnyArray, PcodecError> {
595    let (header, data) =
596        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
597            PcodecError::HeaderDecodeFailed {
598                source: PcoHeaderError(err),
599            }
600        })?;
601
602    let decoded = match header.dtype {
603        PcoDType::U8 => AnyArray::U8(Array::from_shape_vec(
604            &*header.shape,
605            pco::standalone::simple_decompress(data).map_err(|err| {
606                PcodecError::PcoDecodeFailed {
607                    source: PcoCodingError(err),
608                }
609            })?,
610        )?),
611        PcoDType::U16 => AnyArray::U16(Array::from_shape_vec(
612            &*header.shape,
613            pco::standalone::simple_decompress(data).map_err(|err| {
614                PcodecError::PcoDecodeFailed {
615                    source: PcoCodingError(err),
616                }
617            })?,
618        )?),
619        PcoDType::U32 => AnyArray::U32(Array::from_shape_vec(
620            &*header.shape,
621            pco::standalone::simple_decompress(data).map_err(|err| {
622                PcodecError::PcoDecodeFailed {
623                    source: PcoCodingError(err),
624                }
625            })?,
626        )?),
627        PcoDType::U64 => AnyArray::U64(Array::from_shape_vec(
628            &*header.shape,
629            pco::standalone::simple_decompress(data).map_err(|err| {
630                PcodecError::PcoDecodeFailed {
631                    source: PcoCodingError(err),
632                }
633            })?,
634        )?),
635        PcoDType::I8 => AnyArray::I8(Array::from_shape_vec(
636            &*header.shape,
637            pco::standalone::simple_decompress(data).map_err(|err| {
638                PcodecError::PcoDecodeFailed {
639                    source: PcoCodingError(err),
640                }
641            })?,
642        )?),
643        PcoDType::I16 => AnyArray::I16(Array::from_shape_vec(
644            &*header.shape,
645            pco::standalone::simple_decompress(data).map_err(|err| {
646                PcodecError::PcoDecodeFailed {
647                    source: PcoCodingError(err),
648                }
649            })?,
650        )?),
651        PcoDType::I32 => AnyArray::I32(Array::from_shape_vec(
652            &*header.shape,
653            pco::standalone::simple_decompress(data).map_err(|err| {
654                PcodecError::PcoDecodeFailed {
655                    source: PcoCodingError(err),
656                }
657            })?,
658        )?),
659        PcoDType::I64 => AnyArray::I64(Array::from_shape_vec(
660            &*header.shape,
661            pco::standalone::simple_decompress(data).map_err(|err| {
662                PcodecError::PcoDecodeFailed {
663                    source: PcoCodingError(err),
664                }
665            })?,
666        )?),
667        PcoDType::F32 => AnyArray::F32(Array::from_shape_vec(
668            &*header.shape,
669            pco::standalone::simple_decompress(data).map_err(|err| {
670                PcodecError::PcoDecodeFailed {
671                    source: PcoCodingError(err),
672                }
673            })?,
674        )?),
675        PcoDType::F64 => AnyArray::F64(Array::from_shape_vec(
676            &*header.shape,
677            pco::standalone::simple_decompress(data).map_err(|err| {
678                PcodecError::PcoDecodeFailed {
679                    source: PcoCodingError(err),
680                }
681            })?,
682        )?),
683    };
684
685    Ok(decoded)
686}
687
688/// Decompresses the `encoded` data into the `decoded` array.
689///
690/// # Errors
691///
692/// Errors with
693/// - [`PcodecError::HeaderDecodeFailed`] if decoding the header failed
694/// - [`PcodecError::MismatchedDecodeIntoArray`] if the decoded array has the
695///   wrong dtype or shape
696/// - [`PcodecError::PcoDecodeFailed`] if decoding failed with an opaque error
697/// - [`PcodecError::DecodeInvalidShapeHeader`] if the array shape header does
698///   not fit the decoded data
699pub fn decompress_into<T: PcoElement, D: Dimension>(
700    encoded: &[u8],
701    mut decoded: ArrayViewMut<T, D>,
702) -> Result<(), PcodecError> {
703    let (header, data) =
704        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
705            PcodecError::HeaderDecodeFailed {
706                source: PcoHeaderError(err),
707            }
708        })?;
709
710    if T::DTYPE != header.dtype {
711        return Err(PcodecError::MismatchedDecodeIntoArray {
712            source: AnyArrayAssignError::DTypeMismatch {
713                src: header.dtype.into_dtype(),
714                dst: T::DTYPE.into_dtype(),
715            },
716        });
717    }
718
719    if decoded.shape() != &*header.shape {
720        return Err(PcodecError::MismatchedDecodeIntoArray {
721            source: AnyArrayAssignError::ShapeMismatch {
722                src: header.shape.into_owned(),
723                dst: decoded.shape().to_vec(),
724            },
725        });
726    }
727
728    if let Some(slice) = decoded.as_slice_mut() {
729        pco::standalone::simple_decompress_into(data, slice).map_err(|err| {
730            PcodecError::PcoDecodeFailed {
731                source: PcoCodingError(err),
732            }
733        })?;
734        return Ok(());
735    }
736
737    let dec =
738        pco::standalone::simple_decompress(data).map_err(|err| PcodecError::PcoDecodeFailed {
739            source: PcoCodingError(err),
740        })?;
741
742    if dec.len() != decoded.len() {
743        return Err(PcodecError::DecodeInvalidShapeHeader {
744            source: ShapeError::from_kind(ndarray::ErrorKind::IncompatibleShape),
745        });
746    }
747
748    decoded.iter_mut().zip(dec).for_each(|(o, d)| *o = d);
749
750    Ok(())
751}
752
753/// Array element types which can be compressed with pco.
754pub trait PcoElement: Copy + pco::data_types::Number {
755    /// The dtype representation of the type
756    const DTYPE: PcoDType;
757}
758
759impl PcoElement for u8 {
760    const DTYPE: PcoDType = PcoDType::U8;
761}
762
763impl PcoElement for u16 {
764    const DTYPE: PcoDType = PcoDType::U16;
765}
766
767impl PcoElement for u32 {
768    const DTYPE: PcoDType = PcoDType::U32;
769}
770
771impl PcoElement for u64 {
772    const DTYPE: PcoDType = PcoDType::U64;
773}
774
775impl PcoElement for i8 {
776    const DTYPE: PcoDType = PcoDType::I8;
777}
778
779impl PcoElement for i16 {
780    const DTYPE: PcoDType = PcoDType::I16;
781}
782
783impl PcoElement for i32 {
784    const DTYPE: PcoDType = PcoDType::I32;
785}
786
787impl PcoElement for i64 {
788    const DTYPE: PcoDType = PcoDType::I64;
789}
790
791impl PcoElement for f32 {
792    const DTYPE: PcoDType = PcoDType::F32;
793}
794
795impl PcoElement for f64 {
796    const DTYPE: PcoDType = PcoDType::F64;
797}
798
799#[derive(Serialize, Deserialize)]
800struct CompressionHeader<'a> {
801    dtype: PcoDType,
802    #[serde(borrow)]
803    shape: Cow<'a, [usize]>,
804    version: PcodecVersion,
805}
806
807/// Dtypes that pco can compress and decompress
808#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
809#[expect(missing_docs)]
810pub enum PcoDType {
811    #[serde(rename = "u8", alias = "uint8")]
812    U8,
813    #[serde(rename = "u16", alias = "uint16")]
814    U16,
815    #[serde(rename = "u32", alias = "uint32")]
816    U32,
817    #[serde(rename = "u64", alias = "uint64")]
818    U64,
819    #[serde(rename = "i8", alias = "int8")]
820    I8,
821    #[serde(rename = "i16", alias = "int16")]
822    I16,
823    #[serde(rename = "i32", alias = "int32")]
824    I32,
825    #[serde(rename = "i64", alias = "int64")]
826    I64,
827    #[serde(rename = "f32", alias = "float32")]
828    F32,
829    #[serde(rename = "f64", alias = "float64")]
830    F64,
831}
832
833impl PcoDType {
834    #[must_use]
835    /// Convert the [`PcoDType`] into an [`AnyArrayDType`]
836    pub const fn into_dtype(self) -> AnyArrayDType {
837        match self {
838            Self::U8 => AnyArrayDType::U8,
839            Self::U16 => AnyArrayDType::U16,
840            Self::U32 => AnyArrayDType::U32,
841            Self::U64 => AnyArrayDType::U64,
842            Self::I8 => AnyArrayDType::I8,
843            Self::I16 => AnyArrayDType::I16,
844            Self::I32 => AnyArrayDType::I32,
845            Self::I64 => AnyArrayDType::I64,
846            Self::F32 => AnyArrayDType::F32,
847            Self::F64 => AnyArrayDType::F64,
848        }
849    }
850}
851
852impl fmt::Display for PcoDType {
853    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
854        fmt.write_str(match self {
855            Self::U8 => "u8",
856            Self::U16 => "u16",
857            Self::U32 => "u32",
858            Self::U64 => "u64",
859            Self::I8 => "i8",
860            Self::I16 => "i16",
861            Self::I32 => "i32",
862            Self::I64 => "i64",
863            Self::F32 => "f32",
864            Self::F64 => "f64",
865        })
866    }
867}