Saturate.onOverflow

Implements saturation for operators +, - (unary and binary), *, /, %, ^^, &, |, ^, <<, >>, and >>>.

For unary -, onOverflow is called if lhs == Lhs.min and Lhs is a signed type. The function returns Lhs.max.

For binary operators, the result is as follows:

  • Lhs.max if the result overflows in the positive direction, on division by 0, or on shifting right by a negative value
  • Lhs.min if the result overflows in the negative direction
  • 0 if lhs is being shifted left by a negative value, or shifted right by a large positive value
  1. auto onOverflow(Lhs )
  2. typeof(Lhs() + Rhs()) onOverflow(Lhs lhs, Rhs rhs)
    struct Saturate
    static
    typeof(Lhs() + Rhs())
    onOverflow
    (
    string x
    Lhs
    Rhs
    )
    (
    Lhs lhs
    ,
    Rhs rhs
    )
  3. T onLowerBound(Rhs , T bound)
  4. T onUpperBound(Rhs , T bound)

Parameters

x

The operator involved in the opAssign operation

Lhs

The left-hand side type of the operator (Lhs is the first argument to Checked)

Rhs

The right-hand side type in the operator

Return Value

Type: typeof(Lhs() + Rhs())

The saturated result of the operator.

Examples

assert(checked!Saturate(int.max) + 1 == int.max);
assert(checked!Saturate(100) ^^ 10 == int.max);
assert(checked!Saturate(-100) ^^ 10 == int.max);
assert(checked!Saturate(100) / 0 == int.max);
assert(checked!Saturate(100) << -1 == 0);
assert(checked!Saturate(100) << 33 == int.max);
assert(checked!Saturate(100) >> -1 == int.max);
assert(checked!Saturate(100) >> 33 == 0);

Meta