Skip to content

Support uninitialized elements in .assign() and .fill() #798

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
5 changes: 3 additions & 2 deletions src/impl_constructors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,9 @@ where
/// ### Safety
///
/// Accessing uninitalized values is undefined behaviour. You must
/// overwrite *all* the elements in the array after it is created; for
/// example using the methods `.fill()` or `.assign()`.
/// overwrite *all* the elements in the array after it is created; this must
/// be done carefully, for example using the methods `.fill()` or `.assign()`,
/// which are documented to support this use case.
///
/// The contents of the array is indeterminate before initialization and it
/// is an error to perform operations that use the previous values. For
Expand Down
22 changes: 20 additions & 2 deletions src/impl_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1909,23 +1909,41 @@ where
///
/// If their shapes disagree, `rhs` is broadcast to the shape of `self`.
///
/// Assign can be used to overwrite uninitialized data in `self`, if the element
/// type is `Copy`. Only a few array methods will work correctly in this way.
///
/// **Panics** if broadcasting isn’t possible.
pub fn assign<E: Dimension, S2>(&mut self, rhs: &ArrayBase<S2, E>)
where
S: DataMut,
A: Clone,
S2: Data<Elem = A>,
{
self.zip_mut_with(rhs, |x, y| *x = y.clone());
// guarantee validity even for uninited elements and A: Copy (conservative) because we
// traverse using raw pointer
Zip::from(self.raw_view_mut()).and_broadcast(rhs).apply(|x, y|
unsafe {
*x = y.clone();
}
);
}

/// Perform an elementwise assigment to `self` from element `x`.
///
/// Fill can be used to overwrite uninitialized data in `self`, if the element
/// type is `Copy`. Only a few array methods will work correctly in this way.
pub fn fill(&mut self, x: A)
where
S: DataMut,
A: Clone,
{
self.unordered_foreach_mut(move |elt| *elt = x.clone());
// guarantee validity even for uninited elements and A: Copy (conservative) because we
// traverse using raw pointer
Zip::from(self.raw_view_mut()).apply(move |elt|
unsafe {
*elt = x.clone();
}
);
}

fn zip_mut_with_same_shape<B, S2, E, F>(&mut self, rhs: &ArrayBase<S2, E>, mut f: F)
Expand Down