1
Fork 0

Avoid UB when short-circuiting try_map_id for Vec

This commit is contained in:
Alan Egerton 2021-11-27 14:19:24 +00:00
parent 51e15ac709
commit 04f1c09f90
No known key found for this signature in database
GPG key ID: 07CAC3CCA7E0643F

View file

@ -87,7 +87,6 @@ impl<T> IdFunctor for Vec<T> {
// FIXME: We don't really care about panics here and leak // FIXME: We don't really care about panics here and leak
// far more than we should, but that should be fine for now. // far more than we should, but that should be fine for now.
let len = self.len(); let len = self.len();
let mut error = Ok(());
unsafe { unsafe {
self.set_len(0); self.set_len(0);
let start = self.as_mut_ptr(); let start = self.as_mut_ptr();
@ -96,8 +95,16 @@ impl<T> IdFunctor for Vec<T> {
match f(ptr::read(p)) { match f(ptr::read(p)) {
Ok(value) => ptr::write(p, value), Ok(value) => ptr::write(p, value),
Err(err) => { Err(err) => {
error = Err(err); // drop all other elements in self
break; // (current element was "moved" into the call to f)
for j in (0..i).chain(i + 1..len) {
let p = start.add(j);
ptr::drop_in_place(p);
}
// returning will drop self, releasing the allocation
// (len is 0 so elements will not be re-dropped)
return Err(err);
} }
} }
} }
@ -105,7 +112,7 @@ impl<T> IdFunctor for Vec<T> {
// so we don't leak memory. // so we don't leak memory.
self.set_len(len); self.set_len(len);
} }
error.map(|()| self) Ok(self)
} }
} }