Skip to content

Commit c615f45

Browse files
committed
Make ArrayViewMut::into_view public and implement From conversion (#1595)
- Change ArrayViewMut::into_view visibility to pub - Add From<ArrayViewMut> for ArrayView implementation - Add regression tests in tests/views.rs
1 parent 0612fb7 commit c615f45

3 files changed

Lines changed: 57 additions & 2 deletions

File tree

src/arraytraits.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -647,6 +647,17 @@ where
647647
}
648648
}
649649

650+
/// Implementation of `ArrayView::from(ArrayViewMut)`
651+
impl<'a, A, D> From<ArrayViewMut<'a, A, D>> for ArrayView<'a, A, D>
652+
where D: Dimension
653+
{
654+
/// Create a read-only array view from a mutable array view.
655+
fn from(view: ArrayViewMut<'a, A, D>) -> Self
656+
{
657+
view.into_view()
658+
}
659+
}
660+
650661
impl<A, D> From<Array<A, D>> for ArcArray<A, D>
651662
where D: Dimension
652663
{

src/impl_views/conversions.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,8 +273,11 @@ where D: Dimension
273273
impl<'a, A, D> ArrayViewMut<'a, A, D>
274274
where D: Dimension
275275
{
276-
// Convert into a read-only view
277-
pub(crate) fn into_view(self) -> ArrayView<'a, A, D>
276+
/// Convert into a read-only view.
277+
///
278+
/// Unlike [`Self::view`], this method consumes the mutable view and preserves
279+
/// the original lifetime of the data.
280+
pub fn into_view(self) -> ArrayView<'a, A, D>
278281
{
279282
unsafe { ArrayView::new(self.parts.ptr, self.parts.dim, self.parts.strides) }
280283
}

tests/views.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,44 @@ fn cell_view()
1515
}
1616
assert_eq!(a, answer);
1717
}
18+
19+
#[test]
20+
fn test_view_conversion()
21+
{
22+
let mut a = Array2::<f32>::zeros((4, 4));
23+
let view_mut = a.view_mut();
24+
let view = view_mut.into_view();
25+
assert_eq!(view.shape(), &[4, 4]);
26+
27+
let view_mut = a.view_mut();
28+
let view: ArrayView2<'_, f32> = view_mut.into();
29+
assert_eq!(view.shape(), &[4, 4]);
30+
}
31+
32+
#[test]
33+
fn test_view_conversion_lifetime()
34+
{
35+
// Regression test for #1595
36+
struct Foo<'a> {
37+
data: ArrayViewMut2<'a, f32>,
38+
}
39+
40+
impl<'a> Foo<'a> {
41+
fn into_shared(self) -> ArrayView2<'a, f32> {
42+
self.data.into_view()
43+
}
44+
45+
fn into_shared_from(self) -> ArrayView2<'a, f32> {
46+
self.data.into()
47+
}
48+
}
49+
50+
let mut a = Array2::<f32>::zeros((4, 4));
51+
let foo = Foo { data: a.view_mut() };
52+
let shared = foo.into_shared();
53+
assert_eq!(shared.shape(), &[4, 4]);
54+
55+
let foo = Foo { data: a.view_mut() };
56+
let shared = foo.into_shared_from();
57+
assert_eq!(shared.shape(), &[4, 4]);
58+
}

0 commit comments

Comments
 (0)