ndarray/dimension/
remove_axis.rs

1// Copyright 2014-2016 bluss and ndarray developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::{Axis, Dim, Dimension, Ix, Ix0, Ix1};
10
11/// Array shape with a next smaller dimension.
12///
13/// `RemoveAxis` defines a larger-than relation for array shapes:
14/// removing one axis from *Self* gives smaller dimension *Smaller*.
15pub trait RemoveAxis: Dimension {
16    fn remove_axis(&self, axis: Axis) -> Self::Smaller;
17}
18
19impl RemoveAxis for Dim<[Ix; 1]> {
20    #[inline]
21    fn remove_axis(&self, axis: Axis) -> Ix0 {
22        debug_assert!(axis.index() < self.ndim());
23        Ix0()
24    }
25}
26
27impl RemoveAxis for Dim<[Ix; 2]> {
28    #[inline]
29    fn remove_axis(&self, axis: Axis) -> Ix1 {
30        let axis = axis.index();
31        debug_assert!(axis < self.ndim());
32        if axis == 0 {
33            Ix1(get!(self, 1))
34        } else {
35            Ix1(get!(self, 0))
36        }
37    }
38}
39
40macro_rules! impl_remove_axis_array(
41    ($($n:expr),*) => (
42    $(
43        impl RemoveAxis for Dim<[Ix; $n]>
44        {
45            #[inline]
46            fn remove_axis(&self, axis: Axis) -> Self::Smaller {
47                debug_assert!(axis.index() < self.ndim());
48                let mut result = Dim([0; $n - 1]);
49                {
50                    let src = self.slice();
51                    let dst = result.slice_mut();
52                    dst[..axis.index()].copy_from_slice(&src[..axis.index()]);
53                    dst[axis.index()..].copy_from_slice(&src[axis.index() + 1..]);
54                }
55                result
56            }
57        }
58    )*
59    );
60);
61
62impl_remove_axis_array!(3, 4, 5, 6);