Skip to main content

numcodecs_swizzle_reshape/
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-swizzle-reshape
10//! [crates.io]: https://crates.io/crates/numcodecs-swizzle-reshape
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-swizzle-reshape
13//! [docs.rs]: https://docs.rs/numcodecs-swizzle-reshape/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_swizzle_reshape
17//!
18//! Array axis swizzle and reshape codec implementation for the [`numcodecs`]
19//! API.
20
21use std::{
22    borrow::Cow,
23    fmt::{self, Debug},
24};
25
26use ndarray::{Array, ArrayBase, ArrayView, ArrayViewMut, Data, IxDyn};
27use numcodecs::{
28    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
29    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
30};
31use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
32use serde::{
33    Deserialize, Deserializer, Serialize, Serializer,
34    de::{MapAccess, Visitor},
35    ser::SerializeMap,
36};
37use thiserror::Error;
38
39#[cfg(test)]
40use ::serde_json as _;
41
42#[derive(Clone, Serialize, Deserialize, JsonSchema)]
43#[serde(deny_unknown_fields)]
44/// Codec to swizzle/swap the axes of an array and reshape it.
45///
46/// This codec does not store metadata about the original shape of the array.
47/// Since axes that have been combined during encoding cannot be split without
48/// further information, decoding may fail if an output array is not provided.
49///
50/// Swizzling axes is always supported since no additional information about the
51/// array's shape is required to reconstruct it.
52pub struct SwizzleReshapeCodec {
53    /// The permutation of the axes that is applied on encoding.
54    ///
55    /// The permutation is given as a list of axis groups, where each group
56    /// corresponds to one encoded output axis that may consist of several
57    /// decoded input axes. For instance, `[[0], [1, 2]]` flattens a three-
58    /// dimensional array into a two-dimensional one by combining the second and
59    /// third axes.
60    ///
61    /// The permutation also allows specifying a special catch-all remaining
62    /// axes marker:
63    /// - `[[0], {}]` moves the second axis to be the first and appends all
64    ///   other axes afterwards, i.e. the encoded array has the same number
65    ///   of axes as the input array
66    /// - `[[0], [{}]]` in contrast collapses all other axes into one, i.e.
67    ///   the encoded array is two-dimensional
68    pub axes: Vec<AxisGroup>,
69    /// The codec's encoding format version. Do not provide this parameter explicitly.
70    #[serde(default, rename = "_version")]
71    pub version: StaticCodecVersion<1, 0, 0>,
72}
73
74#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
75#[serde(untagged)]
76#[serde(deny_unknown_fields)]
77#[schemars(inline)]
78/// An axis group, potentially from a merged combination of multiple input axes
79pub enum AxisGroup {
80    /// A merged combination of zero, one, or multiple input axes
81    Group(Vec<Axis>),
82    /// All remaining axes, each in a separate single-axis group
83    AllRest(Rest),
84}
85
86#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
87#[serde(untagged)]
88#[serde(deny_unknown_fields)]
89#[schemars(inline)]
90/// An axis or all remaining axes
91pub enum Axis {
92    /// A single axis, as determined by its index
93    Index(usize),
94    /// All remaining axes, combined into one
95    MergedRest(Rest),
96}
97
98impl Codec for SwizzleReshapeCodec {
99    type Error = SwizzleReshapeCodecError;
100
101    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
102        match data {
103            AnyCowArray::U8(data) => Ok(AnyArray::U8(swizzle_reshape(data, &self.axes)?)),
104            AnyCowArray::U16(data) => Ok(AnyArray::U16(swizzle_reshape(data, &self.axes)?)),
105            AnyCowArray::U32(data) => Ok(AnyArray::U32(swizzle_reshape(data, &self.axes)?)),
106            AnyCowArray::U64(data) => Ok(AnyArray::U64(swizzle_reshape(data, &self.axes)?)),
107            AnyCowArray::I8(data) => Ok(AnyArray::I8(swizzle_reshape(data, &self.axes)?)),
108            AnyCowArray::I16(data) => Ok(AnyArray::I16(swizzle_reshape(data, &self.axes)?)),
109            AnyCowArray::I32(data) => Ok(AnyArray::I32(swizzle_reshape(data, &self.axes)?)),
110            AnyCowArray::I64(data) => Ok(AnyArray::I64(swizzle_reshape(data, &self.axes)?)),
111            AnyCowArray::F32(data) => Ok(AnyArray::F32(swizzle_reshape(data, &self.axes)?)),
112            AnyCowArray::F64(data) => Ok(AnyArray::F64(swizzle_reshape(data, &self.axes)?)),
113            data => Err(SwizzleReshapeCodecError::UnsupportedDtype(data.dtype())),
114        }
115    }
116
117    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
118        match encoded {
119            AnyCowArray::U8(encoded) => {
120                Ok(AnyArray::U8(undo_swizzle_reshape(encoded, &self.axes)?))
121            }
122            AnyCowArray::U16(encoded) => {
123                Ok(AnyArray::U16(undo_swizzle_reshape(encoded, &self.axes)?))
124            }
125            AnyCowArray::U32(encoded) => {
126                Ok(AnyArray::U32(undo_swizzle_reshape(encoded, &self.axes)?))
127            }
128            AnyCowArray::U64(encoded) => {
129                Ok(AnyArray::U64(undo_swizzle_reshape(encoded, &self.axes)?))
130            }
131            AnyCowArray::I8(encoded) => {
132                Ok(AnyArray::I8(undo_swizzle_reshape(encoded, &self.axes)?))
133            }
134            AnyCowArray::I16(encoded) => {
135                Ok(AnyArray::I16(undo_swizzle_reshape(encoded, &self.axes)?))
136            }
137            AnyCowArray::I32(encoded) => {
138                Ok(AnyArray::I32(undo_swizzle_reshape(encoded, &self.axes)?))
139            }
140            AnyCowArray::I64(encoded) => {
141                Ok(AnyArray::I64(undo_swizzle_reshape(encoded, &self.axes)?))
142            }
143            AnyCowArray::F32(encoded) => {
144                Ok(AnyArray::F32(undo_swizzle_reshape(encoded, &self.axes)?))
145            }
146            AnyCowArray::F64(encoded) => {
147                Ok(AnyArray::F64(undo_swizzle_reshape(encoded, &self.axes)?))
148            }
149            encoded => Err(SwizzleReshapeCodecError::UnsupportedDtype(encoded.dtype())),
150        }
151    }
152
153    fn decode_into(
154        &self,
155        encoded: AnyArrayView,
156        decoded: AnyArrayViewMut,
157    ) -> Result<(), Self::Error> {
158        match (encoded, decoded) {
159            (AnyArrayView::U8(encoded), AnyArrayViewMut::U8(decoded)) => {
160                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
161            }
162            (AnyArrayView::U16(encoded), AnyArrayViewMut::U16(decoded)) => {
163                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
164            }
165            (AnyArrayView::U32(encoded), AnyArrayViewMut::U32(decoded)) => {
166                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
167            }
168            (AnyArrayView::U64(encoded), AnyArrayViewMut::U64(decoded)) => {
169                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
170            }
171            (AnyArrayView::I8(encoded), AnyArrayViewMut::I8(decoded)) => {
172                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
173            }
174            (AnyArrayView::I16(encoded), AnyArrayViewMut::I16(decoded)) => {
175                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
176            }
177            (AnyArrayView::I32(encoded), AnyArrayViewMut::I32(decoded)) => {
178                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
179            }
180            (AnyArrayView::I64(encoded), AnyArrayViewMut::I64(decoded)) => {
181                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
182            }
183            (AnyArrayView::F32(encoded), AnyArrayViewMut::F32(decoded)) => {
184                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
185            }
186            (AnyArrayView::F64(encoded), AnyArrayViewMut::F64(decoded)) => {
187                undo_swizzle_reshape_into(encoded, decoded, &self.axes)
188            }
189            (encoded, decoded) if encoded.dtype() != decoded.dtype() => {
190                Err(SwizzleReshapeCodecError::MismatchedDecodeIntoArray {
191                    source: AnyArrayAssignError::DTypeMismatch {
192                        src: encoded.dtype(),
193                        dst: decoded.dtype(),
194                    },
195                })
196            }
197            (encoded, _decoded) => Err(SwizzleReshapeCodecError::UnsupportedDtype(encoded.dtype())),
198        }
199    }
200}
201
202impl StaticCodec for SwizzleReshapeCodec {
203    const CODEC_ID: &'static str = "swizzle-reshape.rs";
204
205    type Config<'de> = Self;
206
207    fn from_config(config: Self::Config<'_>) -> Self {
208        config
209    }
210
211    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
212        StaticCodecConfig::from(self)
213    }
214}
215
216#[derive(Debug, Error)]
217/// Errors that may occur when applying the [`SwizzleReshapeCodec`].
218pub enum SwizzleReshapeCodecError {
219    /// [`SwizzleReshapeCodec`] does not support the dtype
220    #[error("SwizzleReshape does not support the dtype {0}")]
221    UnsupportedDtype(AnyArrayDType),
222    /// [`SwizzleReshapeCodec`] cannot decode from an array with merged axes
223    /// without receiving an output array to decode into
224    #[error(
225        "SwizzleReshape cannot decode from an array with merged axes without receiving an output array to decode into"
226    )]
227    CannotDecodeMergedAxes,
228    /// [`SwizzleReshapeCodec`] cannot encode or decode with an invalid axis
229    /// `index` for an array with `ndim` dimensions
230    #[error(
231        "SwizzleReshape cannot encode or decode with an invalid axis {index} for an array with {ndim} dimensions"
232    )]
233    InvalidAxisIndex {
234        /// The out-of-bounds axis index
235        index: usize,
236        /// The number of dimensions of the array
237        ndim: usize,
238    },
239    /// [`SwizzleReshapeCodec`] can only encode or decode with an axis
240    /// permutation `axes` that contains every axis of an array with `ndim`
241    /// dimensions index exactly once
242    #[error(
243        "SwizzleReshape can only encode or decode with an axis permutation {axes:?} that contains every axis of an array with {ndim} dimensions index exactly once"
244    )]
245    InvalidAxisPermutation {
246        /// The invalid permutation of axes
247        axes: Vec<AxisGroup>,
248        /// The number of dimensions of the array
249        ndim: usize,
250    },
251    /// [`SwizzleReshapeCodec`] cannot encode or decode with an axis permutation
252    /// that contains multiple rest-axes markers
253    #[error(
254        "SwizzleReshape cannot encode or decode with an axis permutation that contains multiple rest-axes markers"
255    )]
256    MultipleRestAxes,
257    /// [`SwizzleReshapeCodec`] cannot decode into the provided array
258    #[error("SwizzleReshape cannot decode into the provided array")]
259    MismatchedDecodeIntoArray {
260        /// The source of the error
261        #[from]
262        source: AnyArrayAssignError,
263    },
264}
265
266#[expect(clippy::missing_panics_doc)]
267/// Swizzle and reshape the input `data` array with the new `axes`.
268///
269/// # Errors
270///
271/// Errors with
272/// - [`SwizzleReshapeCodecError::InvalidAxisIndex`] if any axis is out of
273///   bounds
274/// - [`SwizzleReshapeCodecError::InvalidAxisPermutation`] if the `axes`
275///   permutation does not contain every axis index exactly once
276/// - [`SwizzleReshapeCodecError::MultipleRestAxes`] if the `axes` permutation
277///   contains more than one [`Rest`]-axes marker
278pub fn swizzle_reshape<T: Copy, S: Data<Elem = T>>(
279    data: ArrayBase<S, IxDyn>,
280    axes: &[AxisGroup],
281) -> Result<Array<T, IxDyn>, SwizzleReshapeCodecError> {
282    let SwizzleReshapeAxes {
283        permutation,
284        swizzled_shape,
285        new_shape,
286    } = validate_into_axes_shape(&data, axes)?;
287
288    let swizzled: ArrayBase<S, ndarray::Dim<ndarray::IxDynImpl>> = data.permuted_axes(permutation);
289    assert_eq!(swizzled.shape(), swizzled_shape, "incorrect swizzled shape");
290
291    #[expect(clippy::expect_used)] // only panics on an implementation bug
292    let reshaped = swizzled
293        .into_owned()
294        .into_shape_clone(new_shape)
295        .expect("new encoding shape should have the correct number of elements");
296
297    Ok(reshaped)
298}
299
300/// Reverts the swizzle and reshape of the `encoded` array with the `axes` and
301/// returns the original array.
302///
303/// Since the shape of the original array is not known, only permutations of
304/// axes are supported.
305///
306/// # Errors
307///
308/// Errors with
309/// - [`SwizzleReshapeCodecError::CannotDecodeMergedAxes`] if any axes were
310///   merged and thus cannot be split without further information
311/// - [`SwizzleReshapeCodecError::InvalidAxisIndex`] if any axis is out of
312///   bounds
313/// - [`SwizzleReshapeCodecError::InvalidAxisPermutation`] if the `axes`
314///   permutation does not contain every axis index exactly once
315/// - [`SwizzleReshapeCodecError::MultipleRestAxes`] if the `axes` permutation
316///   contains more than one [`Rest`]-axes marker
317pub fn undo_swizzle_reshape<T: Copy, S: Data<Elem = T>>(
318    encoded: ArrayBase<S, IxDyn>,
319    axes: &[AxisGroup],
320) -> Result<Array<T, IxDyn>, SwizzleReshapeCodecError> {
321    if !axes.iter().all(|axis| match axis {
322        AxisGroup::Group(axes) => matches!(axes.as_slice(), [Axis::Index(_)]),
323        AxisGroup::AllRest(Rest) => true,
324    }) {
325        return Err(SwizzleReshapeCodecError::CannotDecodeMergedAxes);
326    }
327
328    let SwizzleReshapeAxes { permutation, .. } = validate_into_axes_shape(&encoded, axes)?;
329
330    let mut inverse_permutation = vec![0; permutation.len()];
331    #[expect(clippy::indexing_slicing)] // all are guaranteed to be in range
332    for (i, p) in permutation.into_iter().enumerate() {
333        inverse_permutation[p] = i;
334    }
335
336    // since no axes were merged, no reshape is needed
337    let unshaped = encoded;
338    let unswizzled = unshaped.permuted_axes(inverse_permutation);
339
340    Ok(unswizzled.into_owned())
341}
342
343#[expect(clippy::missing_panics_doc)]
344#[expect(clippy::needless_pass_by_value)]
345/// Reverts the swizzle and reshape of the `encoded` array with the `axes` and
346/// outputs it into the `decoded` array.
347///
348/// # Errors
349///
350/// Errors with
351/// - [`SwizzleReshapeCodecError::InvalidAxisIndex`] if any axis is out of
352///   bounds
353/// - [`SwizzleReshapeCodecError::InvalidAxisPermutation`] if the `axes`
354///   permutation does not contain every axis index exactly once
355/// - [`SwizzleReshapeCodecError::MultipleRestAxes`] if the `axes` permutation
356///   contains more than one [`Rest`]-axes marker
357/// - [`SwizzleReshapeCodecError::MismatchedDecodeIntoArray`] if the `encoded`
358///   array's shape does not match the shape that swizzling and reshaping an
359///   array of the `decoded` array's shape would have produced
360pub fn undo_swizzle_reshape_into<T: Copy>(
361    encoded: ArrayView<T, IxDyn>,
362    mut decoded: ArrayViewMut<T, IxDyn>,
363    axes: &[AxisGroup],
364) -> Result<(), SwizzleReshapeCodecError> {
365    let SwizzleReshapeAxes {
366        permutation,
367        swizzled_shape,
368        new_shape,
369    } = validate_into_axes_shape(&decoded, axes)?;
370
371    if encoded.shape() != new_shape {
372        return Err(SwizzleReshapeCodecError::MismatchedDecodeIntoArray {
373            source: AnyArrayAssignError::ShapeMismatch {
374                src: encoded.shape().to_vec(),
375                dst: new_shape,
376            },
377        });
378    }
379
380    let mut inverse_permutation = vec![0; decoded.ndim()];
381    #[expect(clippy::indexing_slicing)] // all are guaranteed to be in range
382    for (i, p) in permutation.into_iter().enumerate() {
383        inverse_permutation[p] = i;
384    }
385
386    #[expect(clippy::expect_used)] // only panics on an implementation bug
387    let unshaped = encoded
388        .to_shape(swizzled_shape)
389        .expect("new decoding shape should have the correct number of elements");
390    let unswizzled = unshaped.permuted_axes(inverse_permutation);
391
392    decoded.assign(&unswizzled);
393
394    Ok(())
395}
396
397struct SwizzleReshapeAxes {
398    permutation: Vec<usize>,
399    swizzled_shape: Vec<usize>,
400    new_shape: Vec<usize>,
401}
402
403fn validate_into_axes_shape<T, S: Data<Elem = T>>(
404    array: &ArrayBase<S, IxDyn>,
405    axes: &[AxisGroup],
406) -> Result<SwizzleReshapeAxes, SwizzleReshapeCodecError> {
407    // counts of each axis index, used to check for missing or duplicate axes,
408    //  and for knowing which axes are caught by the rest catch-all
409    let mut axis_index_counts = vec![0_usize; array.ndim()];
410
411    let mut has_rest = false;
412
413    // validate that all axis indices are in bounds and that there is at most
414    //  one catch-all remaining axes marker
415    for group in axes {
416        match group {
417            AxisGroup::Group(axes) => {
418                for axis in axes {
419                    match axis {
420                        Axis::Index(index) => {
421                            if let Some(c) = axis_index_counts.get_mut(*index) {
422                                *c += 1;
423                            } else {
424                                return Err(SwizzleReshapeCodecError::InvalidAxisIndex {
425                                    index: *index,
426                                    ndim: array.ndim(),
427                                });
428                            }
429                        }
430                        Axis::MergedRest(Rest) => {
431                            if std::mem::replace(&mut has_rest, true) {
432                                return Err(SwizzleReshapeCodecError::MultipleRestAxes);
433                            }
434                        }
435                    }
436                }
437            }
438            AxisGroup::AllRest(Rest) => {
439                if std::mem::replace(&mut has_rest, true) {
440                    return Err(SwizzleReshapeCodecError::MultipleRestAxes);
441                }
442            }
443        }
444    }
445
446    // check that each axis is mentioned
447    // - exactly once if no catch-all is used
448    // - at most once if a catch-all is used
449    if !axis_index_counts
450        .iter()
451        .all(|c| if has_rest { *c <= 1 } else { *c == 1 })
452    {
453        return Err(SwizzleReshapeCodecError::InvalidAxisPermutation {
454            axes: axes.to_vec(),
455            ndim: array.ndim(),
456        });
457    }
458
459    // the permutation to apply to the input axes
460    let mut axis_permutation = Vec::with_capacity(array.len());
461    // the shape of the already permuted intermediary array
462    let mut permuted_shape = Vec::with_capacity(array.len());
463    // the shape of the already permuted and grouped output array
464    let mut grouped_shape = Vec::with_capacity(axes.len());
465
466    for axis in axes {
467        match axis {
468            // a group merged all of its axes
469            // an empty group adds an additional axis of size 1
470            AxisGroup::Group(axes) => {
471                let mut new_len = 1;
472                for axis in axes {
473                    match axis {
474                        Axis::Index(index) => {
475                            axis_permutation.push(*index);
476                            permuted_shape.push(array.len_of(ndarray::Axis(*index)));
477                            new_len *= array.len_of(ndarray::Axis(*index));
478                        }
479                        Axis::MergedRest(Rest) => {
480                            for (index, count) in axis_index_counts.iter().enumerate() {
481                                if *count == 0 {
482                                    axis_permutation.push(index);
483                                    permuted_shape.push(array.len_of(ndarray::Axis(index)));
484                                    new_len *= array.len_of(ndarray::Axis(index));
485                                }
486                            }
487                        }
488                    }
489                }
490                grouped_shape.push(new_len);
491            }
492            AxisGroup::AllRest(Rest) => {
493                for (index, count) in axis_index_counts.iter().enumerate() {
494                    if *count == 0 {
495                        axis_permutation.push(index);
496                        permuted_shape.push(array.len_of(ndarray::Axis(index)));
497                        grouped_shape.push(array.len_of(ndarray::Axis(index)));
498                    }
499                }
500            }
501        }
502    }
503
504    Ok(SwizzleReshapeAxes {
505        permutation: axis_permutation,
506        swizzled_shape: permuted_shape,
507        new_shape: grouped_shape,
508    })
509}
510
511#[derive(Copy, Clone, Debug)]
512/// Marker to signify all remaining (not explicitly named) axes
513pub struct Rest;
514
515impl Serialize for Rest {
516    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
517        serializer.serialize_map(Some(0))?.end()
518    }
519}
520
521impl<'de> Deserialize<'de> for Rest {
522    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
523        struct RestVisitor;
524
525        impl<'de> Visitor<'de> for RestVisitor {
526            type Value = Rest;
527
528            fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
529                fmt.write_str("an empty map")
530            }
531
532            fn visit_map<A: MapAccess<'de>>(self, _map: A) -> Result<Self::Value, A::Error> {
533                Ok(Rest)
534            }
535        }
536
537        deserializer.deserialize_map(RestVisitor)
538    }
539}
540
541impl JsonSchema for Rest {
542    fn inline_schema() -> bool {
543        true
544    }
545
546    fn schema_name() -> Cow<'static, str> {
547        Cow::Borrowed("Rest")
548    }
549
550    fn schema_id() -> Cow<'static, str> {
551        Cow::Borrowed(concat!(module_path!(), "::", "Rest"))
552    }
553
554    fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
555        json_schema!({
556            "type": "object",
557            "properties": {},
558            "additionalProperties": false,
559        })
560    }
561}
562
563#[cfg(test)]
564#[expect(clippy::expect_used)]
565mod tests {
566    use ndarray::array;
567
568    use super::*;
569
570    #[test]
571    fn identity() {
572        roundtrip(
573            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
574            &[AxisGroup::AllRest(Rest)],
575            &[2, 2, 2],
576        );
577
578        roundtrip(
579            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
580            &[
581                AxisGroup::Group(vec![Axis::Index(0)]),
582                AxisGroup::Group(vec![Axis::Index(1)]),
583                AxisGroup::AllRest(Rest),
584            ],
585            &[2, 2, 2],
586        );
587        roundtrip(
588            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
589            &[
590                AxisGroup::Group(vec![Axis::Index(0)]),
591                AxisGroup::AllRest(Rest),
592                AxisGroup::Group(vec![Axis::Index(2)]),
593            ],
594            &[2, 2, 2],
595        );
596        roundtrip(
597            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
598            &[
599                AxisGroup::AllRest(Rest),
600                AxisGroup::Group(vec![Axis::Index(1)]),
601                AxisGroup::Group(vec![Axis::Index(2)]),
602            ],
603            &[2, 2, 2],
604        );
605
606        roundtrip(
607            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
608            &[
609                AxisGroup::Group(vec![Axis::Index(0)]),
610                AxisGroup::Group(vec![Axis::Index(1)]),
611                AxisGroup::Group(vec![Axis::MergedRest(Rest)]),
612            ],
613            &[2, 2, 2],
614        );
615        roundtrip(
616            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
617            &[
618                AxisGroup::Group(vec![Axis::Index(0)]),
619                AxisGroup::Group(vec![Axis::MergedRest(Rest)]),
620                AxisGroup::Group(vec![Axis::Index(2)]),
621            ],
622            &[2, 2, 2],
623        );
624        roundtrip(
625            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
626            &[
627                AxisGroup::Group(vec![Axis::MergedRest(Rest)]),
628                AxisGroup::Group(vec![Axis::Index(1)]),
629                AxisGroup::Group(vec![Axis::Index(2)]),
630            ],
631            &[2, 2, 2],
632        );
633    }
634
635    #[test]
636    fn swizzle() {
637        roundtrip(
638            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
639            &[
640                AxisGroup::Group(vec![Axis::Index(0)]),
641                AxisGroup::Group(vec![Axis::Index(1)]),
642                AxisGroup::AllRest(Rest),
643            ],
644            &[2, 2, 2],
645        );
646        roundtrip(
647            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
648            &[
649                AxisGroup::Group(vec![Axis::Index(2)]),
650                AxisGroup::AllRest(Rest),
651                AxisGroup::Group(vec![Axis::Index(1)]),
652            ],
653            &[2, 2, 2],
654        );
655        roundtrip(
656            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
657            &[
658                AxisGroup::AllRest(Rest),
659                AxisGroup::Group(vec![Axis::Index(0)]),
660                AxisGroup::Group(vec![Axis::Index(1)]),
661            ],
662            &[2, 2, 2],
663        );
664
665        roundtrip(
666            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
667            &[
668                AxisGroup::Group(vec![Axis::Index(0)]),
669                AxisGroup::Group(vec![Axis::Index(1)]),
670                AxisGroup::Group(vec![Axis::MergedRest(Rest)]),
671            ],
672            &[2, 2, 2],
673        );
674        roundtrip(
675            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
676            &[
677                AxisGroup::Group(vec![Axis::Index(2)]),
678                AxisGroup::Group(vec![Axis::MergedRest(Rest)]),
679                AxisGroup::Group(vec![Axis::Index(1)]),
680            ],
681            &[2, 2, 2],
682        );
683        roundtrip(
684            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
685            &[
686                AxisGroup::Group(vec![Axis::MergedRest(Rest)]),
687                AxisGroup::Group(vec![Axis::Index(0)]),
688                AxisGroup::Group(vec![Axis::Index(1)]),
689            ],
690            &[2, 2, 2],
691        );
692
693        let mut i = 0;
694        roundtrip(
695            Array::from_shape_fn([3, 1440, 721, 1, 1], |_| {
696                i += 1;
697                i
698            })
699            .into_dyn(),
700            &[
701                AxisGroup::Group(vec![Axis::Index(4)]),
702                AxisGroup::Group(vec![Axis::Index(0)]),
703                AxisGroup::Group(vec![Axis::Index(3)]),
704                AxisGroup::Group(vec![Axis::Index(2)]),
705                AxisGroup::Group(vec![Axis::Index(1)]),
706            ],
707            &[1, 3, 1, 721, 1440],
708        );
709    }
710
711    #[test]
712    fn collapse() {
713        roundtrip(
714            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
715            &[AxisGroup::Group(vec![Axis::MergedRest(Rest)])],
716            &[8],
717        );
718
719        roundtrip(
720            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
721            &[AxisGroup::Group(vec![
722                Axis::Index(0),
723                Axis::Index(1),
724                Axis::Index(2),
725            ])],
726            &[8],
727        );
728        roundtrip(
729            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
730            &[AxisGroup::Group(vec![
731                Axis::Index(2),
732                Axis::Index(1),
733                Axis::Index(0),
734            ])],
735            &[8],
736        );
737        roundtrip(
738            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
739            &[AxisGroup::Group(vec![
740                Axis::Index(1),
741                Axis::MergedRest(Rest),
742            ])],
743            &[8],
744        );
745
746        roundtrip(
747            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
748            &[
749                AxisGroup::Group(vec![Axis::Index(0), Axis::Index(1)]),
750                AxisGroup::AllRest(Rest),
751            ],
752            &[4, 2],
753        );
754        roundtrip(
755            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
756            &[
757                AxisGroup::Group(vec![Axis::Index(2)]),
758                AxisGroup::Group(vec![Axis::Index(1), Axis::Index(0)]),
759            ],
760            &[2, 4],
761        );
762        roundtrip(
763            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
764            &[
765                AxisGroup::Group(vec![Axis::Index(1), Axis::MergedRest(Rest)]),
766                AxisGroup::Group(vec![Axis::Index(0), Axis::Index(2)]),
767            ],
768            &[2, 4],
769        );
770
771        roundtrip(
772            array![[1, 2], [3, 4], [5, 6], [7, 8]].into_dyn(),
773            &[AxisGroup::Group(vec![Axis::MergedRest(Rest)])],
774            &[8],
775        );
776
777        let mut i = 0;
778        roundtrip(
779            Array::from_shape_fn([3, 1440, 721, 1, 1], |_| {
780                i += 1;
781                i
782            })
783            .into_dyn(),
784            &[AxisGroup::Group(vec![
785                Axis::Index(4),
786                Axis::Index(0),
787                Axis::Index(3),
788                Axis::Index(2),
789                Axis::Index(1),
790            ])],
791            &[/* 1 * */ 3 * /* 1 * */ 721 * 1440],
792        );
793    }
794
795    #[test]
796    fn extend() {
797        roundtrip(
798            array![[[1, 2], [3, 4]], [[5, 6], [7, 8]]].into_dyn(),
799            &[
800                AxisGroup::Group(vec![]),
801                AxisGroup::Group(vec![Axis::Index(0)]),
802                AxisGroup::Group(vec![]),
803                AxisGroup::AllRest(Rest),
804                AxisGroup::Group(vec![]),
805                AxisGroup::Group(vec![Axis::Index(2)]),
806                AxisGroup::Group(vec![]),
807            ],
808            &[1, 2, 1, 2, 1, 2, 1],
809        );
810    }
811
812    #[expect(clippy::needless_pass_by_value)]
813    fn roundtrip(data: Array<i32, IxDyn>, axes: &[AxisGroup], swizzle_shape: &[usize]) {
814        let swizzled = swizzle_reshape(data.view(), axes).expect("swizzle should not fail");
815
816        assert_eq!(swizzled.shape(), swizzle_shape);
817
818        let mut unswizzled = Array::zeros(data.shape());
819        undo_swizzle_reshape_into(swizzled.view(), unswizzled.view_mut(), axes)
820            .expect("unswizzle into should not fail");
821
822        assert_eq!(data, unswizzled);
823
824        if axes.iter().any(|a| matches!(a, AxisGroup::Group(a) if a.len() != 1 || a.iter().any(|a| matches!(a, Axis::MergedRest(Rest))))) {
825            undo_swizzle_reshape(swizzled.view(), axes).expect_err("unswizzle should fail");
826        } else {
827            let unswizzled = undo_swizzle_reshape(swizzled.view(), axes).expect("unswizzle should not fail");
828            assert_eq!(data, unswizzled);
829        }
830    }
831}