Issue 22771 - BigInt divMod can return "-0" (negative zero)
Summary: BigInt divMod can return "-0" (negative zero)
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P1 normal
Assignee: No Owner
URL:
Keywords: pull
Depends on:
Blocks:
 
Reported: 2022-02-14 10:07 UTC by Keivan
Modified: 2022-02-14 23:34 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Keivan 2022-02-14 10:07:41 UTC
Overview:

In certain cases, when using divMod from std.bigint, it can return remainder value as "-0" which is incorrect and can causes some logical errors when the remainder is compared with 0.
The issue happens in case of negative numbers and seems to be a logical error in the divMod function: https://github.com/dlang/phobos/blob/2629671c1556a81c4e7eef26e16b331c960e2b6f/std/bigint.d#L2247. Here the sign is directly copied from the dividend without considering that the remainder itself can be zero. Comparing the returned remainder with 0 leads to unexpected logical errors.
The bug is a bit similar to the one resolved here: 
https://issues.dlang.org/show_bug.cgi?id=14124

Steps to Reproduce:

It is present in the currently latest version on D and can be reproduced online currently (https://run.dlang.io/is/YsaAq8) 

Minimal reproduction code:

void main()
{
    import std.bigint;
    
    BigInt dividend = "-50";
    BigInt divisor = "1";
    BigInt quotient, remainder;
    divMod(dividend, divisor, quotient, remainder);
    assert(remainder == 0); // This is false, remainder is "-0"
}
Comment 1 Dlang Bot 2022-02-14 13:26:05 UTC
@dkorpel created dlang/phobos pull request #8379 "Fix issue 22771 - BigInt divMod can return "-0" (negative zero)" fixing this issue:

- Fix issue 22771 - BigInt divMod can return "-0" (negative zero)

https://github.com/dlang/phobos/pull/8379
Comment 2 Dlang Bot 2022-02-14 23:34:42 UTC
dlang/phobos pull request #8379 "Fix issue 22771 - BigInt divMod can return "-0" (negative zero)" was merged into master:

- 6a50e2c05067ecaca8df175e5307f70dbe34c8e1 by dkorpel:
  Fix issue 22771 - BigInt divMod can return "-0" (negative zero)

https://github.com/dlang/phobos/pull/8379