Skip to content

fix negative zero from multiplication/division by zero bigint#143

Merged
michae2 merged 1 commit intocockroachdb:masterfrom
politepixels:master
Mar 17, 2026
Merged

fix negative zero from multiplication/division by zero bigint#143
michae2 merged 1 commit intocockroachdb:masterfrom
politepixels:master

Conversation

@mhaddon
Copy link
Contributor

@mhaddon mhaddon commented Dec 4, 2025

(-1) * 0 was producing a "negative zero" where Sign() returns -1 but String() returns "0". This breaks Cmp() comparisons.

addInline already handles this correctly - just needed the same fix in mulInline, quoInline, and remInline.

result := new(apd.BigInt).Mul(apd.NewBigInt(-1), apd.NewBigInt(0))

result.String() // "0" 
result.Sign()   // -1 (should be 0)
result.Cmp(apd.NewBigInt(0)) // -1 (should be 0)

Same issue with division and remainder when the result is zero.

Added the same zero check to all three functions. Existing tests pass.

@michae2 michae2 self-requested a review December 10, 2025 22:00
Copy link
Contributor

@michae2 michae2 left a comment

Choose a reason for hiding this comment

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

Thanks for the fix! Would you be willing to add a short test to bigint_test.go?

bigint.go Outdated
@@ -326,6 +326,9 @@ func addInline(xVal, yVal uint64, xNeg, yNeg bool) (zVal uint64, zNeg, ok bool)
func mulInline(xVal, yVal uint64, xNeg, yNeg bool) (zVal uint64, zNeg, ok bool) {
hi, lo := bits.Mul64(xVal, yVal)
neg := xNeg != yNeg
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: This could be shortened to neg := xNeg != yNeg && lo != 0 (and same with a couple others).

@mhaddon
Copy link
Contributor Author

mhaddon commented Dec 22, 2025

Is that better?

Copy link
Contributor

@michae2 michae2 left a comment

Choose a reason for hiding this comment

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

Looks great! Thank you!

Assuming tests pass, I'll go ahead and merge.

@michae2 michae2 merged commit cae01a2 into cockroachdb:master Mar 17, 2026
0 of 54 checks passed
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.

2 participants