-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
New lint: unnecessary use of std::ptr::read_unaligned() with slices #4891
Comments
Also, if this is done in a loop, using |
Real-world example of such pattern and its refactoring into safe code: Frommi/miniz_oxide@7bcf211 |
Another real-world example, not yet refactored: https://github.com/cfcosta/poller/blob/c645dc3ffc65237afd41c723aee27ff445b02f12/vendor/diesel/src/sqlite/connection/serialized_value.rs |
in debug and also release? or just in release? |
I've only tried release mode. |
Debug performance is important and I deeply doubt you can beat read_unaligned in debug mode. |
Maybe? https://rust.godbolt.org/z/EdGzzr both implementations are utterly insane due to how many calls there are. Even |
To put this in context, the original motivating example in Even if See also rust-lang/rust#62408 for more info on the potential tradeoff between safety and debug mode performance |
Neither of those problems are related to read unaligned itself. I'm surprised that you don't want a lint for mixing |
During safety-dance audit I've encountered the following unsafe code pattern that can be converted to safe code:
This is common in binary format decoders that need to take a chunk of byte stream and interpret it as a value. The exact target value may vary - it can be any primitive numerical type.
Ever since TryInto got stabilized this can be rewritten in safe code with identical performance, although the safe solution is not really obvious:
This may look like it does a lot of more and would be slower, but rustc produces identical code for both versions.
If converting to f32 or f64, the last line would instead be the following:
f32::from_bits(u32::from_ne_bytes(bytes_to_convert))
See
from_bits()
documentation for more info on converting bytes to floats.The text was updated successfully, but these errors were encountered: