C++ bounded::integer library

Dominikus Dittes Scherkl via Digitalmars-d digitalmars-d at puremagic.com
Tue May 20 02:45:11 PDT 2014


On Sunday, 18 May 2014 at 21:58:54 UTC, bearophile wrote:
> I presume some ways to improve it are to add to core.bitop some 
> D standard intrinsics to detect overflows and carry, to 
> increase run-time performance to sufficient levels. If they are 
> not fast, people will be less willing to used them.
I'm implementing a "safeSigned" type (which uses the bad 
asymmetric min value of signed types as "NaN"), but one 
side-product is a somewhat useful function to check for overflow 
(it doesn't throw, instead the result will be T.max for unsigned 
arguments or T.min for signed arguments). It doesn't create much 
overhead and is very easy to do:

T saveOp(string op, T)(T x, T y) pure @save @nogc if(isIntegral!T 
&& (op=="+" || op=="-" || op=="<<" || op=="*"))
{
    mixin("x "~op~"= y");
    static if(isSigned!T)
    {
       static if(op == "*")
       {
          asm naked { jnc opok; }
       }
       else
       {
          asm naked { jno opok; }
       }
       x = T.min;
    }
    else // unsigned
    {
       asm naked { jnc opok; }
       x = T.max;
    }
    opok:
    return x;
}


More information about the Digitalmars-d mailing list