Fix mulDiv at the u256 boundary with full-width divisor (closes #81)#87
Conversation
mulDiv(MAX, MAX, MAX) should equal MAX but returned a slightly smaller value. The overflow path used a limb-native Knuth Algorithm D divider (divWide) that mis-handled a full multi-limb divisor. Isolated: mulDiv(MAX, 2, 2) was correct (small divisor) but the all-limbs-set divisor case was not. Replace the overflow path's mulWide+divWide with native u512: product = a*b in u512, quotient = product/denominator, null if it exceeds u256. Simple and provably correct. The fast u128 path (the benchmarked 18ns hot path) and the medium u256 path are unchanged -- only the rare a*b-overflows-u256 branch is affected. Removed the now dead, buggy divWide. Surfaced by the test-harness fix (#84).
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe PR fixes a boundary-case bug in ChangesmulDiv Overflow Boundary Correction
🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
What
mulDiv(MAX, MAX, MAX)should equalMAX((2^256-1)^2 / (2^256-1) = 2^256-1) but returned a slightly smaller value.Isolated: the overflow path (taken when
a*bexceeds u256) used a limb-native Knuth Algorithm D divider (divWide) that mis-handled a full multi-limb divisor.mulDiv(MAX, 2, 2)was correct (small divisor); the all-limbs-set divisor was not.Fix
Replaced the overflow path's
mulWide+divWidewith nativeu512:product = @as(u512,a) * @as(u512,b),quotient = product / denominator, return null if it exceeds u256. Simple and provably correct. Removed the now-dead buggydivWide.The benchmarked u128 fast path (18ns) and the medium u256 path are untouched -- only the rare
a*b-overflows-u256 branch changed, so DEX-math performance is unaffected.Verification
The
mulDiv overflow intermediatetest (un-quarantined) passes, all DEX V2/V3 math tests still pass (they exercise mulDiv heavily). Suite: 773 pass, 2 skip. 0.16.0 and 0.17-dev both green.Closes #81
🤖 Generated with Claude Code
Summary by CodeRabbit