Skip to main content

numcodecs_reinterpret/
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-reinterpret
10//! [crates.io]: https://crates.io/crates/numcodecs-reinterpret
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-reinterpret
13//! [docs.rs]: https://docs.rs/numcodecs-reinterpret/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_reinterpret
17//!
18//! Binary reinterpret codec implementation for the [`numcodecs`] API.
19
20use ndarray::{Array, ArrayBase, ArrayView, Data, DataMut, Dimension, ViewRepr};
21use numcodecs::{
22    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
23    ArrayDType, Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
24};
25use schemars::JsonSchema;
26use serde::{Deserialize, Deserializer, Serialize, Serializer};
27use thiserror::Error;
28
29#[cfg(test)]
30use ::serde_json as _;
31
32#[derive(Clone, JsonSchema)]
33#[serde(deny_unknown_fields)]
34/// Codec to reinterpret data between different compatible types.
35///
36/// Note that no conversion happens, only the meaning of the bits changes.
37///
38/// Reinterpreting to bytes, or to a same-sized unsigned integer type, or
39/// without the changing the dtype are supported.
40pub struct ReinterpretCodec {
41    /// Dtype of the encoded data.
42    encode_dtype: AnyArrayDType,
43    /// Dtype of the decoded data
44    decode_dtype: AnyArrayDType,
45    /// The codec's encoding format version. Do not provide this parameter explicitly.
46    #[serde(default)]
47    _version: StaticCodecVersion<1, 0, 0>,
48}
49
50impl ReinterpretCodec {
51    /// Try to create a [`ReinterpretCodec`] that reinterprets the input data
52    /// from `decode_dtype` to `encode_dtype` on encoding, and from
53    /// `encode_dtype` back to `decode_dtype` on decoding.
54    ///
55    /// # Errors
56    ///
57    /// Errors with [`ReinterpretCodecError::InvalidReinterpret`] if
58    /// `encode_dtype` and `decode_dtype` are incompatible.
59    pub fn try_new(
60        encode_dtype: AnyArrayDType,
61        decode_dtype: AnyArrayDType,
62    ) -> Result<Self, ReinterpretCodecError> {
63        #[expect(clippy::match_same_arms)]
64        match (decode_dtype, encode_dtype) {
65            // performing no conversion always works
66            (ty_a, ty_b) if ty_a == ty_b => (),
67            // converting to bytes always works
68            (_, AnyArrayDType::U8) => (),
69            // converting from signed / floating to same-size binary always works
70            (AnyArrayDType::I16, AnyArrayDType::U16)
71            | (AnyArrayDType::I32 | AnyArrayDType::F32, AnyArrayDType::U32)
72            | (AnyArrayDType::I64 | AnyArrayDType::F64, AnyArrayDType::U64) => (),
73            (decode_dtype, encode_dtype) => {
74                return Err(ReinterpretCodecError::InvalidReinterpret {
75                    decode_dtype,
76                    encode_dtype,
77                });
78            }
79        }
80
81        Ok(Self {
82            encode_dtype,
83            decode_dtype,
84            _version: StaticCodecVersion,
85        })
86    }
87
88    #[must_use]
89    /// Create a [`ReinterpretCodec`] that does not change the `dtype`.
90    pub const fn passthrough(dtype: AnyArrayDType) -> Self {
91        Self {
92            encode_dtype: dtype,
93            decode_dtype: dtype,
94            _version: StaticCodecVersion,
95        }
96    }
97
98    #[must_use]
99    /// Create a [`ReinterpretCodec`] that reinterprets `dtype` as
100    /// [bytes][`AnyArrayDType::U8`].
101    pub const fn to_bytes(dtype: AnyArrayDType) -> Self {
102        Self {
103            encode_dtype: AnyArrayDType::U8,
104            decode_dtype: dtype,
105            _version: StaticCodecVersion,
106        }
107    }
108
109    #[must_use]
110    /// Create a  [`ReinterpretCodec`] that reinterprets `dtype` as its
111    /// [binary][`AnyArrayDType::to_binary`] equivalent.
112    pub const fn to_binary(dtype: AnyArrayDType) -> Self {
113        Self {
114            encode_dtype: dtype.to_binary(),
115            decode_dtype: dtype,
116            _version: StaticCodecVersion,
117        }
118    }
119}
120
121impl Codec for ReinterpretCodec {
122    type Error = ReinterpretCodecError;
123
124    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
125        if data.dtype() != self.decode_dtype {
126            return Err(ReinterpretCodecError::MismatchedEncodeDType {
127                configured: self.decode_dtype,
128                provided: data.dtype(),
129            });
130        }
131
132        let encoded = match (data, self.encode_dtype) {
133            (data, dtype) if data.dtype() == dtype => data.into_owned(),
134            (data, AnyArrayDType::U8) => {
135                let mut shape = data.shape().to_vec();
136                if let Some(last) = shape.last_mut() {
137                    *last *= data.dtype().size();
138                }
139                #[expect(unsafe_code)]
140                // Safety: the shape is extended to match the expansion into bytes
141                let encoded =
142                    unsafe { Array::from_shape_vec_unchecked(shape, data.as_bytes().into_owned()) };
143                AnyArray::U8(encoded)
144            }
145            (AnyCowArray::I16(data), AnyArrayDType::U16) => {
146                AnyArray::U16(reinterpret_array(data, |x| {
147                    u16::from_ne_bytes(x.to_ne_bytes())
148                }))
149            }
150            (AnyCowArray::I32(data), AnyArrayDType::U32) => {
151                AnyArray::U32(reinterpret_array(data, |x| {
152                    u32::from_ne_bytes(x.to_ne_bytes())
153                }))
154            }
155            (AnyCowArray::F32(data), AnyArrayDType::U32) => {
156                AnyArray::U32(reinterpret_array(data, f32::to_bits))
157            }
158            (AnyCowArray::I64(data), AnyArrayDType::U64) => {
159                AnyArray::U64(reinterpret_array(data, |x| {
160                    u64::from_ne_bytes(x.to_ne_bytes())
161                }))
162            }
163            (AnyCowArray::F64(data), AnyArrayDType::U64) => {
164                AnyArray::U64(reinterpret_array(data, f64::to_bits))
165            }
166            (data, dtype) => {
167                return Err(ReinterpretCodecError::InvalidReinterpret {
168                    decode_dtype: data.dtype(),
169                    encode_dtype: dtype,
170                });
171            }
172        };
173
174        Ok(encoded)
175    }
176
177    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
178        if encoded.dtype() != self.encode_dtype {
179            return Err(ReinterpretCodecError::MismatchedDecodeDType {
180                configured: self.encode_dtype,
181                provided: encoded.dtype(),
182            });
183        }
184
185        let decoded = match (encoded, self.decode_dtype) {
186            (encoded, dtype) if encoded.dtype() == dtype => encoded.into_owned(),
187            (AnyCowArray::U8(encoded), dtype) => {
188                let mut shape = encoded.shape().to_vec();
189
190                if (encoded.len() % dtype.size()) != 0 {
191                    return Err(ReinterpretCodecError::InvalidEncodedShape { shape, dtype });
192                }
193
194                if let Some(last) = shape.last_mut() {
195                    *last /= dtype.size();
196                }
197
198                let (decoded, ()) = AnyArray::with_zeros_bytes(dtype, &shape, |bytes| {
199                    bytes.copy_from_slice(&AnyCowArray::U8(encoded).as_bytes());
200                });
201
202                decoded
203            }
204            (AnyCowArray::U16(encoded), AnyArrayDType::I16) => {
205                AnyArray::I16(reinterpret_array(encoded, |x| {
206                    i16::from_ne_bytes(x.to_ne_bytes())
207                }))
208            }
209            (AnyCowArray::U32(encoded), AnyArrayDType::I32) => {
210                AnyArray::I32(reinterpret_array(encoded, |x| {
211                    i32::from_ne_bytes(x.to_ne_bytes())
212                }))
213            }
214            (AnyCowArray::U32(encoded), AnyArrayDType::F32) => {
215                AnyArray::F32(reinterpret_array(encoded, f32::from_bits))
216            }
217            (AnyCowArray::U64(encoded), AnyArrayDType::U64) => {
218                AnyArray::I64(reinterpret_array(encoded, |x| {
219                    i64::from_ne_bytes(x.to_ne_bytes())
220                }))
221            }
222            (AnyCowArray::U64(encoded), AnyArrayDType::F64) => {
223                AnyArray::F64(reinterpret_array(encoded, f64::from_bits))
224            }
225            (encoded, dtype) => {
226                return Err(ReinterpretCodecError::InvalidReinterpret {
227                    decode_dtype: dtype,
228                    encode_dtype: encoded.dtype(),
229                });
230            }
231        };
232
233        Ok(decoded)
234    }
235
236    fn decode_into(
237        &self,
238        encoded: AnyArrayView,
239        mut decoded: AnyArrayViewMut,
240    ) -> Result<(), Self::Error> {
241        if encoded.dtype() != self.encode_dtype {
242            return Err(ReinterpretCodecError::MismatchedDecodeDType {
243                configured: self.encode_dtype,
244                provided: encoded.dtype(),
245            });
246        }
247
248        match (encoded, self.decode_dtype) {
249            (encoded, dtype) if encoded.dtype() == dtype => Ok(decoded.assign(&encoded)?),
250            (AnyArrayView::U8(encoded), dtype) => {
251                if decoded.dtype() != dtype {
252                    return Err(ReinterpretCodecError::MismatchedDecodeIntoArray {
253                        source: AnyArrayAssignError::DTypeMismatch {
254                            src: dtype,
255                            dst: decoded.dtype(),
256                        },
257                    });
258                }
259
260                let mut shape = encoded.shape().to_vec();
261
262                if (encoded.len() % dtype.size()) != 0 {
263                    return Err(ReinterpretCodecError::InvalidEncodedShape { shape, dtype });
264                }
265
266                if let Some(last) = shape.last_mut() {
267                    *last /= dtype.size();
268                }
269
270                if decoded.shape() != shape {
271                    return Err(ReinterpretCodecError::MismatchedDecodeIntoArray {
272                        source: AnyArrayAssignError::ShapeMismatch {
273                            src: shape,
274                            dst: decoded.shape().to_vec(),
275                        },
276                    });
277                }
278
279                let () = decoded.with_bytes_mut(|bytes| {
280                    bytes.copy_from_slice(&AnyArrayView::U8(encoded).as_bytes());
281                });
282
283                Ok(())
284            }
285            (AnyArrayView::U16(encoded), AnyArrayDType::I16) => {
286                reinterpret_array_into(encoded, |x| i16::from_ne_bytes(x.to_ne_bytes()), decoded)
287            }
288            (AnyArrayView::U32(encoded), AnyArrayDType::I32) => {
289                reinterpret_array_into(encoded, |x| i32::from_ne_bytes(x.to_ne_bytes()), decoded)
290            }
291            (AnyArrayView::U32(encoded), AnyArrayDType::F32) => {
292                reinterpret_array_into(encoded, f32::from_bits, decoded)
293            }
294            (AnyArrayView::U64(encoded), AnyArrayDType::U64) => {
295                reinterpret_array_into(encoded, |x| i64::from_ne_bytes(x.to_ne_bytes()), decoded)
296            }
297            (AnyArrayView::U64(encoded), AnyArrayDType::F64) => {
298                reinterpret_array_into(encoded, f64::from_bits, decoded)
299            }
300            (encoded, dtype) => Err(ReinterpretCodecError::InvalidReinterpret {
301                decode_dtype: dtype,
302                encode_dtype: encoded.dtype(),
303            }),
304        }?;
305
306        Ok(())
307    }
308}
309
310impl StaticCodec for ReinterpretCodec {
311    const CODEC_ID: &'static str = "reinterpret.rs";
312
313    type Config<'de> = Self;
314
315    fn from_config(config: Self::Config<'_>) -> Self {
316        config
317    }
318
319    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
320        StaticCodecConfig::from(self)
321    }
322}
323
324impl Serialize for ReinterpretCodec {
325    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
326        ReinterpretCodecConfig {
327            encode_dtype: self.encode_dtype,
328            decode_dtype: self.decode_dtype,
329        }
330        .serialize(serializer)
331    }
332}
333
334impl<'de> Deserialize<'de> for ReinterpretCodec {
335    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
336        let config = ReinterpretCodecConfig::deserialize(deserializer)?;
337
338        Self::try_new(config.encode_dtype, config.decode_dtype).map_err(serde::de::Error::custom)
339    }
340}
341
342#[derive(Clone, Serialize, Deserialize)]
343#[serde(rename = "ReinterpretCodec")]
344struct ReinterpretCodecConfig {
345    encode_dtype: AnyArrayDType,
346    decode_dtype: AnyArrayDType,
347}
348
349#[derive(Debug, Error)]
350/// Errors that may occur when applying the [`ReinterpretCodec`].
351pub enum ReinterpretCodecError {
352    /// [`ReinterpretCodec`] cannot cannot bitcast the `decode_dtype` as
353    /// `encode_dtype`
354    #[error("Reinterpret cannot bitcast {decode_dtype} as {encode_dtype}")]
355    InvalidReinterpret {
356        /// Dtype of the configured `decode_dtype`
357        decode_dtype: AnyArrayDType,
358        /// Dtype of the configured `encode_dtype`
359        encode_dtype: AnyArrayDType,
360    },
361    /// [`ReinterpretCodec`] cannot encode the provided dtype which differs
362    /// from the configured dtype
363    #[error(
364        "Reinterpret cannot encode the provided dtype {provided} which differs from the configured dtype {configured}"
365    )]
366    MismatchedEncodeDType {
367        /// Dtype of the `configured` `decode_dtype`
368        configured: AnyArrayDType,
369        /// Dtype of the `provided` array from which the data is to be encoded
370        provided: AnyArrayDType,
371    },
372    /// [`ReinterpretCodec`] cannot decode the provided dtype which differs
373    /// from the configured dtype
374    #[error(
375        "Reinterpret cannot decode the provided dtype {provided} which differs from the configured dtype {configured}"
376    )]
377    MismatchedDecodeDType {
378        /// Dtype of the `configured` `encode_dtype`
379        configured: AnyArrayDType,
380        /// Dtype of the `provided` array from which the data is to be decoded
381        provided: AnyArrayDType,
382    },
383    /// [`ReinterpretCodec`] cannot decode a byte array with `shape` into an array of `dtype`s
384    #[error("Reinterpret cannot decode a byte array of shape {shape:?} into an array of {dtype}-s")]
385    InvalidEncodedShape {
386        /// Shape of the encoded array
387        shape: Vec<usize>,
388        /// Dtype of the array into which the encoded data is to be decoded
389        dtype: AnyArrayDType,
390    },
391    /// [`ReinterpretCodec`] cannot decode into the provided array
392    #[error("Reinterpret cannot decode into the provided array")]
393    MismatchedDecodeIntoArray {
394        /// The source of the error
395        #[from]
396        source: AnyArrayAssignError,
397    },
398}
399
400/// Reinterpret the data elements of the `array` using the provided `reinterpret`
401/// closure. The shape of the data is preserved.
402#[inline]
403pub fn reinterpret_array<T: Copy, U, S: Data<Elem = T>, D: Dimension>(
404    array: ArrayBase<S, D>,
405    reinterpret: impl Fn(T) -> U,
406) -> Array<U, D> {
407    let array = array.into_owned();
408    let (shape, data) = (array.raw_dim(), array.into_raw_vec_and_offset().0);
409
410    let data = data.into_iter().map(reinterpret).collect();
411
412    #[expect(unsafe_code)]
413    // Safety: we have preserved the shape, which comes from a valid array
414    let array = unsafe { Array::from_shape_vec_unchecked(shape, data) };
415
416    array
417}
418
419#[expect(clippy::needless_pass_by_value)]
420/// Reinterpret the data elements of the `encoded` array using the provided
421/// `reinterpret` closure into the `decoded` array.
422///
423/// # Errors
424///
425/// Errors with
426/// - [`ReinterpretCodecError::MismatchedDecodeIntoArray`] if `decoded` does not
427///   contain an array with elements of type `U` or its shape does not match the
428///   `encoded` array's shape
429#[inline]
430pub fn reinterpret_array_into<'a, T: Copy, U: ArrayDType, D: Dimension>(
431    encoded: ArrayView<T, D>,
432    reinterpret: impl Fn(T) -> U,
433    mut decoded: AnyArrayViewMut<'a>,
434) -> Result<(), ReinterpretCodecError>
435where
436    U::RawData<ViewRepr<&'a mut ()>>: DataMut,
437{
438    let Some(decoded) = decoded.as_typed_mut::<U>() else {
439        return Err(ReinterpretCodecError::MismatchedDecodeIntoArray {
440            source: AnyArrayAssignError::DTypeMismatch {
441                src: U::DTYPE,
442                dst: decoded.dtype(),
443            },
444        });
445    };
446
447    if encoded.shape() != decoded.shape() {
448        return Err(ReinterpretCodecError::MismatchedDecodeIntoArray {
449            source: AnyArrayAssignError::ShapeMismatch {
450                src: encoded.shape().to_vec(),
451                dst: decoded.shape().to_vec(),
452            },
453        });
454    }
455
456    // iterate over the elements in standard order
457    for (e, d) in encoded.iter().zip(decoded.iter_mut()) {
458        *d = reinterpret(*e);
459    }
460
461    Ok(())
462}