While String::retain executes it may temporarily leave the String in an inconsistent state, in particular it may contain invalid utf8. This is safe because it restores this invariant before returning, but the caller may skip this by panicing inside the closure and catching the unwind it outside. This allows to create Strings that are not utf8, breaking the library invariant without using unsafe.
For example the following will panic at the final assertion, while I would expect it to never fail when s has type String:
let mut s = "0è0".to_string();
let _ = std::panic::catch_unwind(std::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()); // This will fail
While
String::retainexecutes it may temporarily leave theStringin an inconsistent state, in particular it may contain invalid utf8. This is safe because it restores this invariant before returning, but the caller may skip this by panicing inside the closure and catching the unwind it outside. This allows to createStrings that are not utf8, breaking the library invariant without usingunsafe.For example the following will panic at the final assertion, while I would expect it to never fail when
shas typeString: