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{
17    fn remove_axis(&self, axis: Axis) -> Self::Smaller;
18}
19
20impl RemoveAxis for Dim<[Ix; 1]>
21{
22    #[inline]
23    fn remove_axis(&self, axis: Axis) -> Ix0
24    {
25        debug_assert!(axis.index() < self.ndim());
26        Ix0()
27    }
28}
29
30impl RemoveAxis for Dim<[Ix; 2]>
31{
32    #[inline]
33    fn remove_axis(&self, axis: Axis) -> Ix1
34    {
35        let axis = axis.index();
36        debug_assert!(axis < self.ndim());
37        if axis == 0 {
38            Ix1(get!(self, 1))
39        } else {
40            Ix1(get!(self, 0))
41        }
42    }
43}
44
45macro_rules! impl_remove_axis_array(
46    ($($n:expr),*) => (
47    $(
48        impl RemoveAxis for Dim<[Ix; $n]>
49        {
50            #[inline]
51            fn remove_axis(&self, axis: Axis) -> Self::Smaller {
52                debug_assert!(axis.index() < self.ndim());
53                let mut result = Dim([0; $n - 1]);
54                {
55                    let src = self.slice();
56                    let dst = result.slice_mut();
57                    dst[..axis.index()].copy_from_slice(&src[..axis.index()]);
58                    dst[axis.index()..].copy_from_slice(&src[axis.index() + 1..]);
59                }
60                result
61            }
62        }
63    )*
64    );
65);
66
67impl_remove_axis_array!(3, 4, 5, 6);