Monadic checked arithmetic library - overflow-proof

I have a need to enforce safe overflow handling via type system, and had an idea for "monadic overflow handling". In essence: one can keep using a value that might or might have not overflown already, and only at the end of computation, check overflow status. Kind of line NaN but for integer overflow.

I wasn't able to find anything like this before. There's checked and there are some other crates based on macros and compiler plugins.

Since this is very much a proof of concept, feedback very welcome. In particular about existing crates that I've missed that are either doing just this, or maybe something better.

4 Likes

One interesting thing to point out is that the question mark operator is do-notation for the monad Option. Hence you can do what you're doing with the question mark operator like this:

fn checked_operation(a: i32, b: i32) -> Option<i32> {
    a.checked_add(2)?.checked_div(3)?.checked_add(5)?.checked_mul(b)?.checked_add(1)
}

Obviously your code is more readable.

2 Likes

One thing that bugs me with overflow is that the order of calculations can affect the result, when they wouldn't in mathematics.

In the following example if you swap the two functions, you get panics instead of in-range answers, even though the final answers should be identical.

Assuming you want to always get valid answers if at all possible, it makes analyzing for overflow in a complex formula troublesome.

and it's possible to .check()? as well.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.