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
template safeOp(IntFlagPolicy policy)
bool
cmp
pure @safe nothrow @nogc
(
string op
N
M
)
(
const N left
,
const M right
)
if (
isScalarType!N &&
isScalarType!M
)

Examples

1 import checkedint.sticky : safeOp; // safeOp.cmp() never throws
2 
3 assert(safeOp.cmp!"=="(int.max, 0x7FFF_FFFF));
4 assert(safeOp.cmp!"!="(uint.min, 5u));
5 assert(safeOp.cmp!"<="(int.min, 0));
6 
7 static assert(!__traits(compiles, safeOp.cmp!"=="(uint.max, -1)));
8 static assert(!__traits(compiles, safeOp.cmp!">"(-1, 1u)));

Meta