muls

Multiply two signed integers, checking for overflow.

The overflow is sticky, meaning a sequence of operations can be done and overflow need only be checked at the end.

  1. int muls(int x, int y, bool overflow)
  2. long muls(long x, long y, bool overflow)
    nothrow @safe @nogc pure pragma(inline, true)
    long
    muls
    ()
    (
    long x
    ,
    long y
    ,
    ref bool overflow
    )
  3. cent muls(cent x, cent y, bool overflow)

Parameters

x long

left operand

y long

right operand

overflow bool

set if an overflow occurs, is not affected otherwise

Return Value

Type: long

the product

Examples

bool overflow;
assert(muls(2L, 3L, overflow) == 6);
assert(!overflow);

assert(muls(-200L, 300L, overflow) == -60_000);
assert(!overflow);

assert(muls(1, long.max, overflow) == long.max);
assert(!overflow);

assert(muls(long.min, 1L, overflow) == long.min);
assert(!overflow);

assert(muls(long.max, 2L, overflow) == (long.max * 2));
assert(overflow);
overflow = false;

assert(muls(-1L, long.min, overflow) == long.min);
assert(overflow);

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

assert(muls(0L, 0L, overflow) == 0);
assert(overflow);                   // sticky
bool overflow;
assert(muls(2, 3, overflow) == 6);
assert(!overflow);

assert(muls(-200, 300, overflow) == -60_000);
assert(!overflow);

assert(muls(1, int.max, overflow) == int.max);
assert(!overflow);

assert(muls(int.min, 1, overflow) == int.min);
assert(!overflow);

assert(muls(int.max, 2, overflow) == (int.max * 2));
assert(overflow);

overflow = false;
assert(muls(int.min, -1, overflow) == int.min);
assert(overflow);

assert(muls(0, 0, overflow) == 0);
assert(overflow);                   // sticky

Meta