core.checkedint

This module implements integral arithmetic primitives that check for out-of-range results.

Integral arithmetic operators operate on fixed width types. Results that are not representable in those fixed widths are silently truncated to fit. This module offers integral arithmetic primitives that produce the same results, but set an 'overflow' flag when such truncation occurs. The setting is sticky, meaning that numerous operations can be cascaded and then the flag need only be checked at the end. Whether the operation is signed or unsigned is indicated by an 's' or 'u' suffix, respectively. While this could be achieved without such suffixes by using overloading on the signedness of the types, the suffix makes it clear which is happening without needing to examine the types.

While the generic versions of these functions are computationally expensive relative to the cost of the operation itself, compiler implementations are free to recognize them and generate equivalent and faster code.

The functions here are templates so they can be used with -betterC, as betterC does not link with this library.

References: Fast Integer Overflow Checks

Functions 16

fnint adds()(int x, int y, ref bool overflow) nothrow @safe @nogc pureAdd two signed integers, checking for overflow.
fnlong adds()(long x, long y, ref bool overflow) nothrow @safe @nogc pureditto
fnuint addu()(uint x, uint y, ref bool overflow) nothrow @safe @nogc pureAdd two unsigned integers, checking for overflow (aka carry).
fnulong addu()(ulong x, ulong y, ref bool overflow) nothrow @safe @nogc pureditto
fnint subs()(int x, int y, ref bool overflow) nothrow @safe @nogc pureSubtract two signed integers, checking for overflow.
fnlong subs()(long x, long y, ref bool overflow) nothrow @safe @nogc pureditto
fnuint subu()(uint x, uint y, ref bool overflow) nothrow @safe @nogc pureSubtract two unsigned integers, checking for overflow (aka borrow).
fnulong subu()(ulong x, ulong y, ref bool overflow) nothrow @safe @nogc pureditto
fnint negs()(int x, ref bool overflow) nothrow @safe @nogc pureNegate an integer.
fnlong negs()(long x, ref bool overflow) nothrow @safe @nogc pureditto
fnint muls()(int x, int y, ref bool overflow) nothrow @safe @nogc pureMultiply two signed integers, checking for overflow.
fnlong muls()(long x, long y, ref bool overflow) nothrow @safe @nogc pureditto
fnuint mulu()(uint x, uint y, ref bool overflow) nothrow @safe @nogc pureMultiply two unsigned integers, checking for overflow (aka carry).
fnulong mulu()(ulong x, uint y, ref bool overflow) nothrow @safe @nogc pureditto
fnulong mulu()(ulong x, ulong y, ref bool overflow) nothrow @safe @nogc pureditto
private fnulong mulu_generic()(ulong x, uint y, ref bool overflow) nothrow @safe @nogc pure