savi-lang / savi

A fast language for programmers who are passionate about their craft.
BSD 3-Clause "New" or "Revised" License
156 stars 12 forks source link

Add `saturating_` methods to the `Integer.SafeArithmetic` trait. #302

Closed jemc closed 2 years ago

jemc commented 2 years ago

These new methods return max_value on overflow or min_value on underflow.

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.