View source code
Display the source code in std/checkedint.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.checkedint.opChecked

Defines binary operations with overflow checking for any two integral types. The result type obeys the language rules (even when they may be counterintuitive), and overflow is set if an overflow occurs (including inadvertent change of signedness, e.g. -1 is converted to uint). Conceptually the behavior is:

typeof(mixin(x=="cmp"?"0":"L() "~x~" R()")) opChecked(string x, L, R) (
  const L lhs,
  const R rhs,
  ref bool overflow
)
if (isIntegral!L && isIntegral!R);

  1. Perform the operation in infinite precision
  2. If the infinite-precision result fits in the result type, return it and do not touch overflow
  3. Otherwise, set overflow to true and return an unspecified value

The implementation exploits properties of types and operations to minimize additional work.

Parameters

NameDescription
x The binary operator involved, e.g. /
lhs The left-hand side of the operator
rhs The right-hand side of the operator
overflow The overflow indicator (assigned true in case there's an error)

Returns

The result of the operation, which is the same as the built-in operator

Example

bool overflow;
assert(opChecked!"+"(const short(1), short(1), overflow) == 2 && !overflow);
assert(opChecked!"+"(1, 1, overflow) == 2 && !overflow);
assert(opChecked!"+"(1, 1u, overflow) == 2 && !overflow);
assert(opChecked!"+"(-1, 1u, overflow) == 0 && !overflow);
assert(opChecked!"+"(1u, -1, overflow) == 0 && !overflow);

Example

bool overflow;
assert(opChecked!"-"(1, 1, overflow) == 0 && !overflow);
assert(opChecked!"-"(1, 1u, overflow) == 0 && !overflow);
assert(opChecked!"-"(1u, -1, overflow) == 2 && !overflow);
assert(opChecked!"-"(-1, 1u, overflow) == 0 && overflow);

Example

struct MyHook
{
    static size_t hookToHash(T)(const T payload) nothrow @trusted
    {
        return .hashOf(payload);
    }
}

int[Checked!(int, MyHook)] aa;
Checked!(int, MyHook) var = 42;
aa[var] = 100;

writeln(aa[var]); // 100

int[Checked!(int, Abort)] bb;
Checked!(int, Abort) var2 = 42;
bb[var2] = 100;

writeln(bb[var2]); // 100

Authors

License