Skip to content

Commit 343564e

Browse files
committed
move_into: Add conversion .into_maybe_uninit() for array views
1 parent 117d532 commit 343564e

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/impl_owned_array.rs

+21
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,27 @@ impl<A, D> Array<A, D>
168168
/// drop of any such element, other elements may be leaked.
169169
///
170170
/// ***Panics*** if the shapes don't agree.
171+
///
172+
/// ## Example
173+
///
174+
/// ```
175+
/// use ndarray::Array;
176+
///
177+
/// // Usage example of move_into in safe code
178+
/// let mut a = Array::zeros((10, 10));
179+
/// let b = Array::from_iter(0..100).into_shape((10, 10)).unwrap();
180+
/// // make an MaybeUninit view so that we can *overwrite* into it.
181+
/// b.move_into(a.view_mut().into_maybe_uninit());
182+
///
183+
/// // Usage example using uninit
184+
/// let mut a = Array::uninit((10, 10));
185+
/// let b = Array::from_iter(0..100).into_shape((10, 10)).unwrap();
186+
/// b.move_into(&mut a);
187+
/// unsafe {
188+
/// // we can now promise we have fully initialized `a`.
189+
/// let a = a.assume_init();
190+
/// }
191+
/// ```
171192
pub fn move_into<'a, AM>(self, new_array: AM)
172193
where
173194
AM: Into<ArrayViewMut<'a, MaybeUninit<A>, D>>,

src/impl_views/conversions.rs

+16
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
// except according to those terms.
88

99
use alloc::slice;
10+
use std::mem::MaybeUninit;
1011

1112
use crate::imp_prelude::*;
1213

@@ -133,6 +134,21 @@ where
133134
self.into_raw_view_mut().cast::<MathCell<A>>().deref_into_view()
134135
}
135136
}
137+
138+
/// Return the array view as a view of `MaybeUninit<A>` elements
139+
///
140+
/// This conversion leaves the elements as they were (presumably initialized), but
141+
/// they are represented with the `MaybeUninit<A>` type. Effectively this means that
142+
/// the elements can be overwritten without dropping the old element in its place.
143+
/// (In some situations this is not what you want, while for `Copy` elements it makes
144+
/// no difference at all.)
145+
pub fn into_maybe_uninit(self) -> ArrayViewMut<'a, MaybeUninit<A>, D> {
146+
// Safe because: A and MaybeUninit<A> have the same representation;
147+
// and we can go from initialized to (maybe) not unconditionally.
148+
unsafe {
149+
self.into_raw_view_mut().cast::<MaybeUninit<A>>().deref_into_view_mut()
150+
}
151+
}
136152
}
137153

138154
/// Private array view methods

0 commit comments

Comments
 (0)