Skip to main content

numcodecs_identity/
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-identity
10//! [crates.io]: https://crates.io/crates/numcodecs-identity
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-identity
13//! [docs.rs]: https://docs.rs/numcodecs-identity/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_identity
17//!
18//! Identity codec implementation for the [`numcodecs`] API.
19
20use numcodecs::{
21    AnyArray, AnyArrayAssignError, AnyArrayView, AnyArrayViewMut, AnyCowArray, Codec, StaticCodec,
22    StaticCodecConfig, StaticCodecVersion,
23};
24use schemars::JsonSchema;
25use serde::{Deserialize, Serialize};
26use thiserror::Error;
27
28#[cfg(test)]
29use ::serde_json as _;
30
31#[derive(Clone, Serialize, Deserialize, JsonSchema)]
32#[serde(deny_unknown_fields)]
33/// Identity codec which applies the identity function, i.e. passes through the
34/// input unchanged during encoding and decoding.
35pub struct IdentityCodec {
36    /// The codec's encoding format version. Do not provide this parameter explicitly.
37    #[serde(default, rename = "_version")]
38    pub version: StaticCodecVersion<1, 0, 0>,
39}
40
41impl Codec for IdentityCodec {
42    type Error = IdentityCodecError;
43
44    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
45        Ok(data.into_owned())
46    }
47
48    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
49        Ok(encoded.into_owned())
50    }
51
52    fn decode_into(
53        &self,
54        encoded: AnyArrayView,
55        mut decoded: AnyArrayViewMut,
56    ) -> Result<(), Self::Error> {
57        Ok(decoded.assign(&encoded)?)
58    }
59}
60
61impl StaticCodec for IdentityCodec {
62    const CODEC_ID: &'static str = "identity.rs";
63
64    type Config<'de> = Self;
65
66    fn from_config(config: Self::Config<'_>) -> Self {
67        config
68    }
69
70    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
71        StaticCodecConfig::from(self)
72    }
73}
74
75#[derive(Debug, Error)]
76/// Errors that may occur when applying the [`IdentityCodec`].
77pub enum IdentityCodecError {
78    /// [`IdentityCodec`] cannot decode into the provided array
79    #[error("Identity cannot decode into the provided array")]
80    MismatchedDecodeIntoArray {
81        /// The source of the error
82        #[from]
83        source: AnyArrayAssignError,
84    },
85}