1
Fork 0

Rollup merge of #78499 - SkiFire13:fix-string-retain, r=m-ou-se

Prevent String::retain from creating non-utf8 strings when abusing panic

Fixes #78498

The idea is the same as `Vec::drain`, set the len to 0 so that nobody can observe the broken invariant if it escapes the function (in this case if `f` panics)
This commit is contained in:
Jonas Schievink 2020-10-29 17:05:28 +01:00 committed by GitHub
commit 48c4afbf9c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 4 deletions

View file

@ -1235,6 +1235,10 @@ impl String {
let mut del_bytes = 0;
let mut idx = 0;
unsafe {
self.vec.set_len(0);
}
while idx < len {
let ch = unsafe { self.get_unchecked(idx..len).chars().next().unwrap() };
let ch_len = ch.len_utf8();
@ -1255,10 +1259,8 @@ impl String {
idx += ch_len;
}
if del_bytes > 0 {
unsafe {
self.vec.set_len(len - del_bytes);
}
unsafe {
self.vec.set_len(len - del_bytes);
}
}