tcbrindle / flux

A C++20 library for sequence-orientated programming
https://tristanbrindle.com/flux/
Boost Software License 1.0
472 stars 29 forks source link

Safe numerics #125

Closed tcbrindle closed 5 hours ago

tcbrindle commented 1 year ago

This PR does a whole lot of things.

Firstly, we define some concepts for integers. Specifically, the flux::num::integral concept is satisfied by any std::integral type except bool, char, wchar_t and the various charN_ts. We also have corresponding signed_integral and unsigned_integral concepts.

Next, we define some functions which perform unchecked integer operations, namely:

These work call the built-in operators (and so can cause UB for signed types), but require both arguments to be the same type, and cast the result back to their argument type -- that is, there is no promotion, so unchecked_add(short, short) returns a short, not an int. The intention is that these can be used in places where signed UB can allow extra optimisations, and explicitly acknowledge that you're doing something dangerous.

Next is a set of wrapping functions:

These work by casting their arguments to an unsigned type, performing the operation, and casting back to the starting type. They never cause UB, and can be used to specifically document that you want wrapping semantics.

Next is a set of functions which check whether overflow occurred:

These return a (T, bool) pair which safely performs the operation (as if by wrapping) and reports whether overflow occurred. They use compiler builtins in GCC and Clang. These work for unsigned types as well as signed types, so you can test whether your size_t overflowed.

Then we have a set of checked arithmetic functions:

These raise a flux::runtime_error if overflow occurs (or division by zero for the last two functions), regardless of the compiled checking policy.

Finally, we have

These perform overflow/divide-by-zero checks according to the configured policies. By default, they trap on overflow in debug mode or wrap in release mode.

Phew!

codecov[bot] commented 1 year ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 98.81%. Comparing base (2e5ce71) to head (5ad5023). Report is 23 commits behind head on main.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #125 +/- ## ========================================== + Coverage 98.30% 98.81% +0.50% ========================================== Files 71 71 Lines 2485 2534 +49 ========================================== + Hits 2443 2504 +61 + Misses 42 30 -12 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.