Skip to content

Commit

Permalink
Fix Clone impl for miri stacked-borrows model
Browse files Browse the repository at this point in the history
This clone impl would sucessfully run under `MIRIFLAGS=-Zmiri-tree-borrows`
but failed with stacked borrows.  Instead of cloning the extra capacity into
the new vec.  Create a new vector with the correct capacity then extend it
with the cloned contents of the other vector. This can be done safely.
  • Loading branch information
ratmice committed Mar 9, 2024
1 parent abd6aaf commit aaa349b
Showing 1 changed file with 4 additions and 9 deletions.
13 changes: 4 additions & 9 deletions src/core/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,15 +242,10 @@ impl<T: Clone> Clone for OptionCore<T> {
// is important for us.
// - The memory after its length is probably uninitialized.
//
// To fix both issues, we get a slice to the complete memory of the
// original `Vec` and create a `Vec` from it. Then we reset the length
// to the old value. Both is safe as all the elements that are included
// and excluded by the "fake length" are `None`.
let data = unsafe {
let mut data_clone = self.data.get_unchecked(0..self.data.capacity()).to_vec();
data_clone.set_len(self.data.len());
data_clone
};
// To fix both issues, we create a new vec with the appopriate capacity
// and extend it with the values of the other.
let mut data = Vec::with_capacity(self.data.capacity());
data.extend(self.data.iter().cloned());

Self { data }
}
Expand Down

0 comments on commit aaa349b

Please sign in to comment.