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.82.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#[derive(Clone, Serialize, Deserialize, JsonSchema)]
29#[serde(deny_unknown_fields)]
30/// Identity codec which applies the identity function, i.e. passes through the
31/// input unchanged during encoding and decoding.
32pub struct IdentityCodec {
33 /// The codec's encoding format version. Do not provide this parameter explicitly.
34 #[serde(default, rename = "_version")]
35 pub version: StaticCodecVersion<1, 0, 0>,
36}
37
38impl Codec for IdentityCodec {
39 type Error = IdentityCodecError;
40
41 fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
42 Ok(data.into_owned())
43 }
44
45 fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
46 Ok(encoded.into_owned())
47 }
48
49 fn decode_into(
50 &self,
51 encoded: AnyArrayView,
52 mut decoded: AnyArrayViewMut,
53 ) -> Result<(), Self::Error> {
54 Ok(decoded.assign(&encoded)?)
55 }
56}
57
58impl StaticCodec for IdentityCodec {
59 const CODEC_ID: &'static str = "identity.rs";
60
61 type Config<'de> = Self;
62
63 fn from_config(config: Self::Config<'_>) -> Self {
64 config
65 }
66
67 fn get_config(&self) -> StaticCodecConfig<Self> {
68 StaticCodecConfig::from(self)
69 }
70}
71
72#[derive(Debug, Error)]
73/// Errors that may occur when applying the [`IdentityCodec`].
74pub enum IdentityCodecError {
75 /// [`IdentityCodec`] cannot decode into the provided array
76 #[error("Identity cannot decode into the provided array")]
77 MismatchedDecodeIntoArray {
78 /// The source of the error
79 #[from]
80 source: AnyArrayAssignError,
81 },
82}