Skip to content

Commit 926ddbe

Browse files
committed
add strided constructor for ArrayView
1 parent e1fef22 commit 926ddbe

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

src/lib.rs

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -709,8 +709,8 @@ impl<S, A, D> ArrayBase<S, D>
709709
/// Create an array from a vector and interpret it according to the
710710
/// provided dimensions and strides. No allocation needed.
711711
///
712-
/// **Panics** if the stride and dimensions point outside the vector's
713-
/// memory.
712+
/// Checks whether `dim` and `strides` are compatible with the vector's
713+
/// length, returning an `Err` if not compatible.
714714
pub fn from_vec_dim_stride(dim: D,
715715
strides: D,
716716
v: Vec<A>
@@ -756,6 +756,44 @@ impl<'a, A, D> ArrayView<'a, A, D>
756756
}
757757
}
758758

759+
/// Create an `ArrayView` borrowing its data from a slice.
760+
///
761+
/// Checks whether `dim` and `strides` are compatible with the slice's
762+
/// length, returning an `Err` if not compatible.
763+
///
764+
/// ```
765+
/// use ndarray::ArrayView;
766+
/// use ndarray::arr3;
767+
///
768+
/// let s = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
769+
/// let a = ArrayView::from_slice_dim_stride((2, 3, 2),
770+
/// (1, 4, 2),
771+
/// s).unwrap();
772+
///
773+
/// assert!(
774+
/// a == arr3(&[[[0, 2],
775+
/// [4, 6],
776+
/// [8, 10]],
777+
/// [[1, 3],
778+
/// [5, 7],
779+
/// [9, 11]]])
780+
/// );
781+
/// assert!(a.strides() == &[1, 4, 2]);
782+
/// ```
783+
pub fn from_slice_dim_stride(dim: D,
784+
strides: D,
785+
s: &'a [A]
786+
) -> Result<Self, StrideError>
787+
{
788+
dimension::can_index_slice(s,
789+
&dim,
790+
&strides).map(|_| {
791+
unsafe {
792+
Self::new_(s.as_ptr(), dim, strides)
793+
}
794+
})
795+
}
796+
759797
#[inline]
760798
fn into_base_iter(self) -> Baseiter<'a, A, D> {
761799
unsafe {

0 commit comments

Comments
 (0)