These new methods return max_value on overflow or min_value on underflow.
saturating_add
saturating_subtract
saturating_multiply
These new methods should be preferred over using +!, -!, and *!
in a try block with max_value and/or min_value in the else block,
which was otherwise the established pattern for acheiving this.
The _add and _subtract methods use efficient LLVM intrinsics
dedicated to this purpose, while the _multiply method has no
associated LLVM intrinsic, and thus is implemented using
the *! method as a basis for detecting overflow/underflow efficiently.
In working on this, it was noticed that a few test cases were missing
for +!, -!, and *!, so those tests were added here as well.
Also the doc comments for those methods were fixed up/improved
to better cover how negative numbers behave in signed integers,
and to mention the saturating variants and when to use those instead.
These new methods return
max_value
on overflow ormin_value
on underflow.saturating_add
saturating_subtract
saturating_multiply
These new methods should be preferred over using
+!
,-!
, and*!
in atry
block withmax_value
and/ormin_value
in the else block, which was otherwise the established pattern for acheiving this.The
_add
and_subtract
methods use efficient LLVM intrinsics dedicated to this purpose, while the_multiply
method has no associated LLVM intrinsic, and thus is implemented using the*!
method as a basis for detecting overflow/underflow efficiently.In working on this, it was noticed that a few test cases were missing for
+!
,-!
, and*!
, so those tests were added here as well. Also the doc comments for those methods were fixed up/improved to better cover how negative numbers behave in signed integers, and to mention the saturating variants and when to use those instead.