Skip to content

Handle wide power-of-two divisors in exact division#1271

Open
tob-joe wants to merge 1 commit into
RustCrypto:masterfrom
tob-joe:fix-div-exact-wide-power-of-two
Open

Handle wide power-of-two divisors in exact division#1271
tob-joe wants to merge 1 commit into
RustCrypto:masterfrom
tob-joe:fix-div-exact-wide-power-of-two

Conversation

@tob-joe
Copy link
Copy Markdown

@tob-joe tob-joe commented Jun 4, 2026

Summary

UintRef::div_exact could panic when the divisor was wider than the dividend and had exactly as many trailing zeros as the dividend precision. In that case, exact division should report inexact division rather than indexing or shifting past the dividend.

Fix

ensure_trailing_zeros now handles zero-count requests that cover the full dividend width by checking whether the whole dividend is zero, instead of indexing the limb at nlimbs.

After the trailing-zero exactness check, div_exact now uses an unbounded right shift so shifting by the full dividend precision produces zero instead of panicking.

Tests

Added a regression test covering exact division of U128::ONE by a U256 power-of-two divisor at bit position U128::BITS.

Verified with:

cargo test --all-features --test uint div_exact_wide_power_of_two_divisor_is_inexact -- --exact

This work was completed by Trail of Bits as part of the Patch The Planet project in collaboration with OpenAI. The issue was identified primarily by the Codex coding agent, and manually reviewed before submission.

Avoid indexing past the dividend when checking whether it has at least as many trailing zeros as a wider divisor.

Use an unbounded right shift after the trailing-zero exactness check so shifting by the full dividend precision produces zero instead of panicking.

Add a regression test for exact division by a wider power-of-two divisor.

Co-authored-by: GPT 5.5 <gpt-5.5@openai.com>
@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 4, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.00%. Comparing base (4c6f87d) to head (809148c).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1271   +/-   ##
=======================================
  Coverage   90.99%   91.00%           
=======================================
  Files         189      189           
  Lines       22139    22141    +2     
=======================================
+ Hits        20146    20150    +4     
+ Misses       1993     1991    -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant