From 1a5c668cbf7341d7c0afe452f0ac809307bce9a6 Mon Sep 17 00:00:00 2001 From: bluss Date: Thu, 25 Jan 2018 19:14:45 +0100 Subject: [PATCH] FEAT: Add .reborrow() methods to array views `ArrayView<'a, T, D>` is invariant in parameters `T` and `'a`, because `ArrayBase` is invariant in the parameter `S` because the array base is using the projection `::Elem` in the struct definition. This means that the equivalent of the `&'a T -> &'b T` conversion (valid whenever `'a: 'b` is not naturally available for array views; we can provide it manually, with a method. --- src/impl_views.rs | 21 ++++++++++++++++++++- tests/array.rs | 14 ++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/impl_views.rs b/src/impl_views.rs index 7f9329af0..7bd96ffeb 100644 --- a/src/impl_views.rs +++ b/src/impl_views.rs @@ -82,6 +82,16 @@ impl<'a, A, D> ArrayView<'a, A, D> ArrayView::new_(ptr, dim, strides) } + /// Convert the view into an `ArrayView<'b, A, D>` where `'b` is a lifetime + /// outlived by `'a'`. + pub fn reborrow<'b>(self) -> ArrayView<'b, A, D> + where 'a: 'b + { + unsafe { + ArrayView::new_(self.as_ptr(), self.dim, self.strides) + } + } + /// Split the array view along `axis` and return one view strictly before the /// split and one view after the split. /// @@ -133,7 +143,6 @@ impl<'a, A, D> ArrayView<'a, A, D> None } } - } @@ -328,6 +337,16 @@ impl<'a, A, D> ArrayViewMut<'a, A, D> ArrayViewMut::new_(ptr, dim, strides) } + /// Convert the view into an `ArrayViewMut<'b, A, D>` where `'b` is a lifetime + /// outlived by `'a'`. + pub fn reborrow<'b>(mut self) -> ArrayViewMut<'b, A, D> + where 'a: 'b + { + unsafe { + ArrayViewMut::new_(self.as_mut_ptr(), self.dim, self.strides) + } + } + /// Split the array view along `axis` and return one mutable view strictly /// before the split and one mutable view after the split. /// diff --git a/tests/array.rs b/tests/array.rs index ef98f4a42..a98a743a2 100644 --- a/tests/array.rs +++ b/tests/array.rs @@ -40,6 +40,20 @@ fn test_matmul_rcarray() } } +#[allow(unused)] +fn arrayview_shrink_lifetime<'a, 'b: 'a>(view: ArrayView1<'b, f64>) + -> ArrayView1<'a, f64> +{ + view.reborrow() +} + +#[allow(unused)] +fn arrayviewmut_shrink_lifetime<'a, 'b: 'a>(view: ArrayViewMut1<'b, f64>) + -> ArrayViewMut1<'a, f64> +{ + view.reborrow() +} + #[test] fn test_mat_mul() { // smoke test, a big matrix multiplication of uneven size