Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/arraytraits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,17 @@ where
}
}

/// Implementation of `ArrayView::from(ArrayViewMut)`
impl<'a, A, D> From<ArrayViewMut<'a, A, D>> for ArrayView<'a, A, D>
where D: Dimension
{
/// Create a read-only array view from a mutable array view.
fn from(view: ArrayViewMut<'a, A, D>) -> Self
{
view.into_view()
}
}

impl<A, D> From<Array<A, D>> for ArcArray<A, D>
where D: Dimension
{
Expand Down
7 changes: 5 additions & 2 deletions src/impl_views/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,11 @@ where D: Dimension
impl<'a, A, D> ArrayViewMut<'a, A, D>
where D: Dimension
{
// Convert into a read-only view
pub(crate) fn into_view(self) -> ArrayView<'a, A, D>
/// Convert into a read-only view.
///
/// This method consumes the mutable view and returns an `ArrayView` that
/// preserves the original lifetime `'a` of the data.
pub fn into_view(self) -> ArrayView<'a, A, D>
{
unsafe { ArrayView::new(self.parts.ptr, self.parts.dim, self.parts.strides) }
}
Expand Down
45 changes: 45 additions & 0 deletions tests/views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,48 @@ fn cell_view()
}
assert_eq!(a, answer);
}

#[test]
fn test_view_conversion()
{
let mut a = Array2::<f32>::zeros((4, 4));
let view_mut = a.view_mut();
let view = view_mut.into_view();
assert_eq!(view.shape(), &[4, 4]);

let view_mut = a.view_mut();
let view: ArrayView2<'_, f32> = view_mut.into();
assert_eq!(view.shape(), &[4, 4]);
}

#[test]
fn test_view_conversion_lifetime()
{
// Regression test for #1595
struct Foo<'a>
{
data: ArrayViewMut2<'a, f32>,
}

impl<'a> Foo<'a>
{
fn into_shared(self) -> ArrayView2<'a, f32>
{
self.data.into_view()
}

fn into_shared_from(self) -> ArrayView2<'a, f32>
{
self.data.into()
}
}

let mut a = Array2::<f32>::zeros((4, 4));
let foo = Foo { data: a.view_mut() };
let shared = foo.into_shared();
assert_eq!(shared.shape(), &[4, 4]);

let foo = Foo { data: a.view_mut() };
let shared = foo.into_shared_from();
assert_eq!(shared.shape(), &[4, 4]);
}
Loading