|
| 1 | +// Copyright 2021 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 | + |
| 9 | +use crate::imp_prelude::*; |
| 10 | + |
| 11 | +use crate::data_traits::RawDataSubst; |
| 12 | + |
| 13 | +use num_complex::Complex; |
| 14 | + |
| 15 | + |
| 16 | +pub trait MultiElement { |
| 17 | + type Elem; |
| 18 | + const LEN: usize; |
| 19 | +} |
| 20 | + |
| 21 | +impl<A, const N: usize> MultiElement for [A; N] { |
| 22 | + type Elem = A; |
| 23 | + const LEN: usize = N; |
| 24 | +} |
| 25 | + |
| 26 | +impl<A> MultiElement for Complex<A> { |
| 27 | + type Elem = A; |
| 28 | + const LEN: usize = 2; |
| 29 | +} |
| 30 | + |
| 31 | +impl<'a, A, D, const N: usize> ArrayView<'a, [A; N], D> |
| 32 | +where |
| 33 | + D: Dimension, |
| 34 | +{ |
| 35 | + /// |
| 36 | + /// Note: expanding a zero-element array leads to a new axis of length zero, |
| 37 | + /// i.e. the array becomes empty. |
| 38 | + /// |
| 39 | + /// **Panics** if the product of non-zero axis lengths overflows `isize`. |
| 40 | + pub fn expand(self, new_axis: Axis) -> ArrayView<'a, A, D::Larger> { |
| 41 | + let mut strides = self.strides.insert_axis(new_axis); |
| 42 | + let mut dim = self.dim.insert_axis(new_axis); |
| 43 | + let len = N as isize; |
| 44 | + for ax in 0..strides.ndim() { |
| 45 | + if Axis(ax) == new_axis { |
| 46 | + continue; |
| 47 | + } |
| 48 | + if dim[ax] > 1 { |
| 49 | + strides[ax] = ((strides[ax] as isize) * len) as usize; |
| 50 | + } |
| 51 | + } |
| 52 | + dim[new_axis.index()] = N; |
| 53 | + // TODO nicer assertion |
| 54 | + crate::dimension::size_of_shape_checked(&dim).unwrap(); |
| 55 | + |
| 56 | + // safe because |
| 57 | + // size still fits in isize; |
| 58 | + // new strides are adapted to new element type, inside the same allocation. |
| 59 | + unsafe { |
| 60 | + ArrayBase::from_data_ptr(self.data.data_subst(), self.ptr.cast()) |
| 61 | + .with_strides_dim(strides, dim) |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments