Skip to content
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

bitv: Avoid undefined behavior in mask_for_bits #2

Merged
merged 1 commit into from
Dec 10, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/libcollections/bit.rs
Original file line number Diff line number Diff line change
@@ -177,7 +177,7 @@ fn blocks_for_bits(bits: uint) -> uint {
/// Computes the bitmask for the final word of the vector
fn mask_for_bits(bits: uint) -> u32 {
// Note especially that a perfect multiple of u32::BITS should mask all 1s.
!0u32 >> (u32::BITS - bits % u32::BITS)
!0u32 >> (u32::BITS - bits % u32::BITS) % u32::BITS
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, is it not the case that the internal % can be removed completely because math?

That is (x - (y mod j)) mod j == (x - y) mod (some multiple of j, because uints wrap) mod j

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, as long as uint wrapping is defined behavior, it could even be (-bits) % u32::BITS. I expect the optimizer will already figure that out, but I can compare.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes, that works too! Nice.

All of our primitive integer types overflow in a defined way.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bah, -bits triggers #[warn(unsigned_negation)]. But (0 - bits) % u32::BITS is fine. As I expected, the optimized codegen is identical - do you still care to have this updated?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If codegen is fine, I'm happy with leaving it like this for semantic value. multiple modulo stuff hurts my brain, for the most part.

}

impl Bitv {