Skip to content

Commit

Permalink
move_into: Add conversion .into_maybe_uninit() for array views
Browse files Browse the repository at this point in the history
  • Loading branch information
bluss committed Apr 22, 2021
1 parent 1d9e677 commit 6831d04
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/impl_owned_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,27 @@ impl<A, D> Array<A, D>
/// drop of any such element, other elements may be leaked.
///
/// ***Panics*** if the shapes don't agree.
///
/// ## Example
///
/// ```
/// use ndarray::Array;
///
/// // Usage example of move_into in safe code
/// let mut a = Array::zeros((10, 10));
/// let b = Array::from_iter(0..100).into_shape((10, 10)).unwrap();
/// // make an MaybeUninit view so that we can *overwrite* into it.
/// b.move_into(a.view_mut().into_maybe_uninit());
///
/// // Usage example using uninit
/// let mut a = Array::uninit((10, 10));
/// let b = Array::from_iter(0..100).into_shape((10, 10)).unwrap();
/// b.move_into(&mut a);
/// unsafe {
/// // we can now promise we have fully initialized `a`.
/// let a = a.assume_init();
/// }
/// ```
pub fn move_into<'a, AM>(self, new_array: AM)
where
AM: Into<ArrayViewMut<'a, MaybeUninit<A>, D>>,
Expand Down
16 changes: 16 additions & 0 deletions src/impl_views/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// except according to those terms.

use alloc::slice;
use std::mem::MaybeUninit;

use crate::imp_prelude::*;

Expand Down Expand Up @@ -133,6 +134,21 @@ where
self.into_raw_view_mut().cast::<MathCell<A>>().deref_into_view()
}
}

/// Return the array view as a view of `MaybeUninit<A>` elements
///
/// This conversion leaves the elements as they were (presumably initialized), but
/// they are represented with the `MaybeUninit<A>` type. Effectively this means that
/// the elements can be overwritten without dropping the old element in its place.
/// (In some situations this is not what you want, while for `Copy` elements it makes
/// no difference at all.)
pub fn into_maybe_uninit(self) -> ArrayViewMut<'a, MaybeUninit<A>, D> {
// Safe because: A and MaybeUninit<A> have the same representation;
// and we can go from initialized to (maybe) not unconditionally.
unsafe {
self.into_raw_view_mut().cast::<MaybeUninit<A>>().deref_into_view_mut()
}
}
}

/// Private array view methods
Expand Down

0 comments on commit 6831d04

Please sign in to comment.