numcodecs 0.3.1

numcodecs API for buffer compression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::{borrow::Cow, error::Error, fmt, marker::PhantomData};

use schemars::{JsonSchema, Schema, SchemaGenerator, generate::SchemaSettings, json_schema};
use semver::{Version, VersionReq};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

use crate::{AnyArray, AnyArrayView, AnyArrayViewMut, AnyCowArray};

/// Compression codec that [`encode`][`Codec::encode`]s and
/// [`decode`][`Codec::decode`]s numeric n-dimensional arrays.
pub trait Codec: 'static + Send + Sync + Clone {
    /// Error type that may be returned during [`encode`][`Codec::encode`]ing
    /// and [`decode`][`Codec::decode`]ing.
    type Error: 'static + Send + Sync + Error;

    /// Encodes the `data` and returns the result.
    ///
    /// # Errors
    ///
    /// Errors if encoding the buffer fails.
    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error>;

    /// Decodes the `encoded` data and returns the result.
    ///
    /// # Errors
    ///
    /// Errors if decoding the buffer fails.
    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error>;

    /// Decodes the `encoded` data and writes the result into the provided
    /// `decoded` output.
    ///
    /// The output must have the correct type and shape.
    ///
    /// # Errors
    ///
    /// Errors if decoding the buffer fails.
    fn decode_into(
        &self,
        encoded: AnyArrayView,
        decoded: AnyArrayViewMut,
    ) -> Result<(), Self::Error>;
}

/// Statically typed compression codec.
pub trait StaticCodec: Codec {
    /// Codec identifier.
    const CODEC_ID: &'static str;

    /// Configuration type, from which the codec can be created infallibly.
    ///
    /// The `config` must *not* contain an `id` field.
    ///
    /// The config *must* be compatible with JSON encoding and have a schema.
    type Config<'de>: Serialize + Deserialize<'de> + JsonSchema;

    /// Instantiate a codec from its `config`uration.
    fn from_config(config: Self::Config<'_>) -> Self;

    /// Get the configuration for this codec.
    ///
    /// The [`StaticCodecConfig`] ensures that the returned config includes an
    /// `id` field with the codec's [`StaticCodec::CODEC_ID`].
    fn get_config(&self) -> StaticCodecConfig<'_, Self>;
}

/// Dynamically typed compression codec.
///
/// Every codec that implements [`StaticCodec`] also implements [`DynCodec`].
pub trait DynCodec: Codec {
    /// Type object type for this codec.
    type Type: DynCodecType;

    /// Returns the type object for this codec.
    fn ty(&self) -> Self::Type;

    /// Serializes the configuration parameters for this codec.
    ///
    /// The config *must* include an `id` field with the
    /// [`DynCodecType::codec_id`], for which the
    /// [`serialize_codec_config_with_id`] helper function may be used.
    ///
    /// The config *must* be compatible with JSON encoding.
    ///
    /// # Errors
    ///
    /// Errors if serializing the codec configuration fails.
    fn get_config<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>;
}

/// Type object for dynamically typed compression codecs.
pub trait DynCodecType: 'static + Send + Sync {
    /// Type of the instances of this codec type object.
    type Codec: DynCodec<Type = Self>;

    /// Codec identifier.
    fn codec_id(&self) -> &str;

    /// JSON schema for the codec's configuration.
    fn codec_config_schema(&self) -> Schema;

    /// Instantiate a codec of this type from a serialized `config`uration.
    ///
    /// The `config` must *not* contain an `id` field. If the `config` *may*
    /// contain one, use the [`codec_from_config_with_id`] helper function.
    ///
    /// The `config` *must* be compatible with JSON encoding.
    ///
    /// # Errors
    ///
    /// Errors if constructing the codec fails.
    fn codec_from_config<'de, D: Deserializer<'de>>(
        &self,
        config: D,
    ) -> Result<Self::Codec, D::Error>;
}

impl<T: StaticCodec> DynCodec for T {
    type Type = StaticCodecType<Self>;

    fn ty(&self) -> Self::Type {
        StaticCodecType::of()
    }

    fn get_config<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        <T as StaticCodec>::get_config(self).serialize(serializer)
    }
}

/// Type object for statically typed compression codecs.
pub struct StaticCodecType<T: StaticCodec> {
    _marker: PhantomData<T>,
}

impl<T: StaticCodec> StaticCodecType<T> {
    /// Statically obtain the type for a statically typed codec.
    #[must_use]
    pub const fn of() -> Self {
        Self {
            _marker: PhantomData::<T>,
        }
    }
}

impl<T: StaticCodec> DynCodecType for StaticCodecType<T> {
    type Codec = T;

    fn codec_id(&self) -> &str {
        T::CODEC_ID
    }

    fn codec_config_schema(&self) -> Schema {
        let mut settings = SchemaSettings::draft2020_12();
        // TODO: perhaps this could be done as a more generally applicable
        //       transformation instead
        settings.inline_subschemas = true;
        settings
            .into_generator()
            .into_root_schema_for::<T::Config<'static>>()
    }

    fn codec_from_config<'de, D: Deserializer<'de>>(
        &self,
        config: D,
    ) -> Result<Self::Codec, D::Error> {
        let config = T::Config::deserialize(config)?;
        Ok(T::from_config(config))
    }
}

/// Utility struct to serialize a [`StaticCodec`]'s [`StaticCodec::Config`]
/// together with its [`StaticCodec::CODEC_ID`]
#[derive(Serialize, Deserialize)]
#[serde(bound = "")]
pub struct StaticCodecConfig<'a, T: StaticCodec> {
    #[serde(default)]
    id: StaticCodecId<T>,
    /// The configuration parameters
    #[serde(flatten)]
    #[serde(borrow)]
    pub config: T::Config<'a>,
}

impl<'a, T: StaticCodec> StaticCodecConfig<'a, T> {
    /// Wraps the `config` so that it can be serialized together with its
    /// [`StaticCodec::CODEC_ID`]
    #[must_use]
    pub const fn new(config: T::Config<'a>) -> Self {
        Self {
            id: StaticCodecId::of(),
            config,
        }
    }
}

impl<'a, T: StaticCodec> From<&T::Config<'a>> for StaticCodecConfig<'a, T>
where
    T::Config<'a>: Clone,
{
    fn from(config: &T::Config<'a>) -> Self {
        Self::new(config.clone())
    }
}

struct StaticCodecId<T: StaticCodec>(PhantomData<T>);

impl<T: StaticCodec> StaticCodecId<T> {
    #[must_use]
    pub const fn of() -> Self {
        Self(PhantomData::<T>)
    }
}

impl<T: StaticCodec> Default for StaticCodecId<T> {
    fn default() -> Self {
        Self::of()
    }
}

impl<T: StaticCodec> Serialize for StaticCodecId<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        T::CODEC_ID.serialize(serializer)
    }
}

impl<'de, T: StaticCodec> Deserialize<'de> for StaticCodecId<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let id = Cow::<str>::deserialize(deserializer)?;
        let id = &*id;

        if id != T::CODEC_ID {
            return Err(serde::de::Error::custom(format!(
                "expected codec id {:?} but found {id:?}",
                T::CODEC_ID,
            )));
        }

        Ok(Self::of())
    }
}

/// Utility function to serialize a codec's config together with its
/// [`DynCodecType::codec_id`].
///
/// This function may be useful when implementing the [`DynCodec::get_config`]
/// method.
///
/// # Errors
///
/// Errors if serializing the codec configuration fails.
pub fn serialize_codec_config_with_id<T: Serialize, C: DynCodec, S: Serializer>(
    config: &T,
    codec: &C,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    #[derive(Serialize)]
    struct DynCodecConfigWithId<'a, T> {
        id: &'a str,
        #[serde(flatten)]
        config: &'a T,
    }

    DynCodecConfigWithId {
        id: codec.ty().codec_id(),
        config,
    }
    .serialize(serializer)
}

/// Utility function to instantiate a codec of the given `ty`, where the
/// `config` *may* still contain an `id` field.
///
/// If the `config` does *not* contain an `id` field, use
/// [`DynCodecType::codec_from_config`] instead.
///
/// # Errors
///
/// Errors if constructing the codec fails.
pub fn codec_from_config_with_id<'de, T: DynCodecType, D: Deserializer<'de>>(
    ty: &T,
    config: D,
) -> Result<T::Codec, D::Error> {
    let mut config = Value::deserialize(config)?;

    if let Some(config) = config.as_object_mut() {
        if let Some(id) = config.remove("id") {
            let codec_id = ty.codec_id();

            if !matches!(id, Value::String(ref id) if id == codec_id) {
                return Err(serde::de::Error::custom(format!(
                    "expected codec id {codec_id:?} but found {id}"
                )));
            }
        }
    }

    ty.codec_from_config(config)
        .map_err(serde::de::Error::custom)
}

/// Marker type that represents the semantic version of a codec.
///
/// The codec's version can be decoupled from its implementation version to
/// allow implementation changes that have no effect on the codec's semantics
/// or encoded representation.
///
/// `StaticCodecVersion`s serialize transparently to their equivalent
/// [`Version`]s. On deserialization, the deserialized [`Version`] is checked
/// to be compatible (`^`) with the `StaticCodecVersion`, i.e. the
/// `StaticCodecVersion` must be of a the same or a newer compatible version.
pub struct StaticCodecVersion<const MAJOR: u64, const MINOR: u64, const PATCH: u64>;

impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> StaticCodecVersion<MAJOR, MINOR, PATCH> {
    /// Extract the semantic version.
    #[must_use]
    pub const fn version() -> Version {
        Version::new(MAJOR, MINOR, PATCH)
    }
}

#[expect(clippy::expl_impl_clone_on_copy)]
impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> Clone
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> Copy
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
}

impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> fmt::Debug
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        <semver::Version as fmt::Debug>::fmt(&Self::version(), fmt)
    }
}

impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> fmt::Display
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        <semver::Version as fmt::Display>::fmt(&Self::version(), fmt)
    }
}

impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> Default
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
    fn default() -> Self {
        Self
    }
}

impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> Serialize
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        Self::version().serialize(serializer)
    }
}

impl<'de, const MAJOR: u64, const MINOR: u64, const PATCH: u64> Deserialize<'de>
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let version = Version::deserialize(deserializer)?;

        let requirement = VersionReq {
            comparators: vec![semver::Comparator {
                op: semver::Op::Caret,
                major: version.major,
                minor: Some(version.minor),
                patch: Some(version.patch),
                pre: version.pre,
            }],
        };

        if !requirement.matches(&Self::version()) {
            return Err(serde::de::Error::custom(format!(
                "{Self} does not fulfil {requirement}"
            )));
        }

        Ok(Self)
    }
}

impl<const MAJOR: u64, const MINOR: u64, const PATCH: u64> JsonSchema
    for StaticCodecVersion<MAJOR, MINOR, PATCH>
{
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("StaticCodecVersion")
    }

    fn schema_id() -> Cow<'static, str> {
        Cow::Borrowed(concat!(module_path!(), "::", "StaticCodecVersion"))
    }

    fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "type": "string",
            "pattern": r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
            "description": "A semver.org compliant semantic version number.",
        })
    }
}