safeOp

Implements various integer math operations with error checking.

safeOp strives to mimic the standard integer math operations in every way, except:

  • If the operation is generally untrustworthy - for example, signed/unsigned comparisons - a compile-time error is generated. The message will usually suggest a workaround.
  • At runtime, if the result is mathematically incorrect an appropriate IntFlag will be raised.

The runtime error-signalling policy may be selected using the policy template parameter.

Members

Aliases

cmp
alias cmp = safeOp!(IntFlagPolicy.none).cmp
Undocumented in source.

Functions

abs
N abs(N num)

Get the absolute value of num.

binary
OpType!(N, op, M) binary(N left, M right)
N binary(N left, M right)

Perform the binary (two-argument) integer operation specified by op.

  • Unsafe signed/unsigned operations will generate a compile-time error.
  • +, -, *, /, and % are checked for overflow at runtime.
  • / and % are also checked for divide-by-zero.
  • <<, >>, and >>> are checked to verify that right >= 0 and right < (8 * typeof(left).sizeof). Otherwise, IntFlag.undef is raised.


Note also:

  • The shift operators are not checked for overflow and should not be used for multiplication, division, or exponentiation. Instead, use mulPow2() and divPow2(), which internally use the bitshifts for speed, but check for overflow and correctly handle negative values.
  • Likewise, modPow2() should be used for remainders instead of &.
  • ^^ and ^^= will remain disabled in favour of pow until DMD issues 15288 and 15412 are fixed.


Like the standard equiavlents, the assignment operators (+=, -=, *=, etc.) take left by ref and will overwrite it with the result of the operation.

bsf
int bsf(N num)

core.bitop.bsf without the undefined behaviour. safeOp.bsf(0) will raise IntFlag.undef.

bsr
int bsr(N num)

core.bitop.bsr without the undefined behaviour. safeOp.bsr(0) will raise IntFlag.undef.

cmp
bool cmp(N left, M right)

Compare left and right using op.

divPow2
auto divPow2(N left, M exp)

Equivalent to left / pow(2, exp), but faster and works with a wider range of inputs. This is a safer alternative to left >> exp that is still very fast.

ilogb
int ilogb(N num)

Get the base 2 logarithm of abs(num), rounded down to the nearest integer.

modPow2
auto modPow2(N left, M exp)

Equivalent to left % pow(2, exp), but faster and works with a wider range of inputs. This is a safer alternative to left & ((1 << exp) - 1) that is still very fast.

mulPow2
auto mulPow2(N left, M exp)

Equivalent to left * pow(2, exp), but faster and works with a wider range of inputs. This is a safer alternative to left << exp that is still very fast.

pow
CallType!(std.math.pow, N, M) pow(N base, M exp)

Raise base to the exp power.

unary
N unary(N num)

Perform the unary (single-argument) integer operation specified by op.

Meta