safeOp.cmp

Compare left and right using op.

Unsafe signed/unsigned comparisons will trigger a compile-time error. Possible solutions include:

  • Should the inputs really have different signedness? Changing the type of one to match the other is the simplest solution.
  • Consider using smartOp.cmp(), instead, as it can safely do signed/unsigned comparisons.
  • Alternately, checkedint.to() can be used to safely convert the type of one input, with runtime bounds checking.


Direct comparisons between boolean values and numeric ones are also forbidden. Make the intent explicit:

  • numeric == cast(N)boolean
  • (numeric != 0) == boolean
  1. bool cmp(N left, M right)
    template safeOp(IntFlagPolicy policy)
    pure @safe nothrow @nogc
    static if(policy == IntFlagPolicy.none)
    bool
    cmp
    (
    string op
    N
    M
    )
    (
    const N left
    ,
    const M right
    )
    if (
    isScalarType!N &&
    isScalarType!M
    )
  2. alias cmp = safeOp!(IntFlagPolicy.none).cmp

Examples

import checkedint.sticky : safeOp; // safeOp.cmp() never throws

assert(safeOp.cmp!"=="(int.max, 0x7FFF_FFFF));
assert(safeOp.cmp!"!="(uint.min, 5u));
assert(safeOp.cmp!"<="(int.min, 0));

static assert(!__traits(compiles, safeOp.cmp!"=="(uint.max, -1)));
static assert(!__traits(compiles, safeOp.cmp!">"(-1, 1u)));

Meta