www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 14785] New: Some corner cases are not handled properly by

https://issues.dlang.org/show_bug.cgi?id=14785

          Issue ID: 14785
           Summary: Some corner cases are not handled properly by
                    core.checkedint.
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: normal
          Priority: P1
         Component: druntime
          Assignee: nobody puremagic.com
          Reporter: thomas.bockman gmail.com

** Test cases that currently fail **

import core.checkedint;
void main(string[] args)
{
    bool overflow = false;
    assert(subs(-1L, long.min, overflow) == long.max);
    assert(!overflow); // Assertion failure

    overflow = false;
    assert(muls(-1L, long.min, overflow) == long.min); // FPE
    assert(overflow);
}

** Proposed fix **

long subs(long x, long y, ref bool overflow)
{
    long r = cast(ulong)x - cast(ulong)y;
    if (x <  0 && y >= 0 && r >= 0 ||
        x >= 0 && y <  0 && (r <  0 || y == long.min))
        overflow = true;
    return r;
}

long muls(long x, long y, ref bool overflow)
{
    long r = cast(ulong)x * cast(ulong)y;
    enum not0or1 = ~1L;
    if((x & not0or1) && ((r == y)? r : (r / x) != y))
        overflow = true;
    return r;
}

--
Jul 07 2015