Skip to content
Merged
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
10 changes: 6 additions & 4 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() };
Comment on lines +1238 to 1243
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RalfJung this was brought to my attention by @DJMcNab (the author of retain_more), as somewhat suspicious - it's calling get_unchecked on a &str obtained via auto-deref which is zero-length now. So we more or less expect this needs to go through a raw pointer directly or something similar.

Copy link
Contributor Author

@SkiFire13 SkiFire13 Feb 26, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! I guess another fix would be using a DropGuard for setting the length at the end of the loop. This way it's not necessary to set the length to 0 anymore because its drop implementation would called even in case of panic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've opened #82554, let me know what you think about it

let ch_len = ch.len_utf8();
Expand All @@ -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);
}
}

Expand Down
15 changes: 15 additions & 0 deletions library/alloc/tests/string.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::borrow::Cow;
use std::collections::TryReserveError::*;
use std::ops::Bound::*;
use std::panic;

pub trait IntoCow<'a, B: ?Sized>
where
Expand Down Expand Up @@ -378,6 +379,20 @@ fn test_retain() {

s.retain(|_| false);
assert_eq!(s, "");

let mut s = String::from("0è0");
let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| {
let mut count = 0;
s.retain(|_| {
count += 1;
match count {
1 => false,
2 => true,
_ => panic!(),
}
});
}));
assert!(std::str::from_utf8(s.as_bytes()).is_ok());
}

#[test]
Expand Down