new lint: manual_offset_from_unsigned#16688
Open
jaroslawroszyk wants to merge 1 commit intorust-lang:masterfrom
Open
new lint: manual_offset_from_unsigned#16688jaroslawroszyk wants to merge 1 commit intorust-lang:masterfrom
jaroslawroszyk wants to merge 1 commit intorust-lang:masterfrom
Conversation
Collaborator
|
r? @dswij rustbot has assigned @dswij. Use Why was this reviewer chosen?The reviewer was selected based on:
|
cb163b0 to
f6e6ab2
Compare
|
Lintcheck changes for 03cb98a
This comment will be updated if you push new changes |
f6e6ab2 to
03cb98a
Compare
Author
|
@rustbot ready |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #16156
Description
This PR introduces a new lint manual_offset_from_unsigned that detects patterns like ptr1.offset_from(ptr2) as usize and suggests replacing them with ptr1.offset_from_unsigned(ptr2).
Why is this important?
The offset_from_unsigned method (stabilized in Rust 1.87.0) explicitly handles the safety precondition that the pointer must be greater than or equal to the argument. Using this method is more idiomatic, potentially allows for better compiler optimizations, and makes the code's intent clearer than a raw cast to usize.
Example
Can be replaced with:
Implementation Details
The implementation handles both raw pointers and NonNull types. It uses a helper function to "peel" blocks and unsafe scopes to find the inner method call even when it's wrapped in a block.
I've followed the contribution guidelines
I've added UI tests for the new lint
I've run
cargo dev update_lintschangelog:
[manual_offset_from_unsigned]: Added a lint to detect manual conversion fromoffset_fromtousize.