-
-
Notifications
You must be signed in to change notification settings - Fork 14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is there a way to use potentially panicking code in a #[no_panic] function #16
Comments
Ah, I found a way: #[inline(never)]
unsafe extern "C" fn is_utf8(ptr: *const u8, len: usize) -> bool {
let slice = slice::from_raw_parts(ptr, len);
str::from_utf8(slice).is_ok()
}
fn from_utf8(data: &[u8]) -> Result<&str, ()> {
match unsafe{ is_utf8(data.as_ptr(), data.len()) } {
true => Ok(unsafe{ str::from_utf8_unchecked(s) }),
false => Err(()),
}
} This is ugly as hell and uses And thank you for |
I don't know a better way, but I've added your trick to the readme. Thanks! |
For future readers: if you don't use This means, in /// Checks if a string is UTF-8
#[inline(never)]
extern "C" fn is_utf8(slice: &[u8]) -> bool {
std::panic::catch_unwind(|| str::from_utf8(slice).is_ok()).unwrap_or(false)
} which is neither unsafe nor does it allow a panic to bubble across FFI-boundaries and invoke UB. |
While this sounds contra-intuitive, there are std/core-library functions where I can/have to assume that they are correct and won't panic (e.g.
str::from_utf8
). However since the compiler is unable to prove for some functions that they are panic-free, I cannot use them.Is there a way to "trust" such a function that it will never panic? Since due to the huge amounts of
unsafe
code in std/core, I have to rely on their correctness anyway; so it would make no difference for my crate's correctness assumptions…The text was updated successfully, but these errors were encountered: