zarrs_metadata_ext/codec/registered/
bytes.rs

1use derive_more::{Display, From};
2use serde::{Deserialize, Serialize};
3
4use zarrs_metadata::{ConfigurationSerialize, Endianness};
5
6/// A wrapper to handle various versions of `bytes` codec configuration parameters.
7#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Debug, Display, From)]
8#[non_exhaustive]
9#[serde(untagged)]
10pub enum BytesCodecConfiguration {
11    /// Version 1.0.
12    V1(BytesCodecConfigurationV1),
13}
14
15impl ConfigurationSerialize for BytesCodecConfiguration {}
16
17/// `bytes` codec configuration parameters (version 1.0).
18#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Debug, Display)]
19#[serde(deny_unknown_fields)]
20#[display("{}", serde_json::to_string(self).unwrap_or_default())]
21pub struct BytesCodecConfigurationV1 {
22    /// The target endianness. Required if the data type is larger than one byte.
23    /// A string equal to either "big" or "little" in JSON.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub endian: Option<Endianness>,
26}
27
28impl BytesCodecConfigurationV1 {
29    /// Create a new `bytes` codec configuration given an optional [`Endianness`].
30    #[must_use]
31    pub const fn new(endian: Option<Endianness>) -> Self {
32        Self { endian }
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn codec_bytes_big() {
42        serde_json::from_str::<BytesCodecConfiguration>(r#"{"endian":"big"}"#).unwrap();
43    }
44
45    #[test]
46    fn codec_bytes_little() {
47        serde_json::from_str::<BytesCodecConfiguration>(r#"{"endian":"little"}"#).unwrap();
48    }
49
50    #[test]
51    fn codec_bytes_empty() {
52        serde_json::from_str::<BytesCodecConfiguration>(r#"{}"#).unwrap();
53    }
54
55    #[test]
56    fn codec_bytes_invalid() {
57        assert!(serde_json::from_str::<BytesCodecConfiguration>(r#"{"endian":""}"#).is_err());
58    }
59}