A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/rust-lang/rust/issues/78498 below:

String::retain allows safely creating invalid (non-utf8) strings when abusing panic · Issue #78498 · rust-lang/rust · GitHub

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4