4 ms·
Slightly related, I wonder why the return type for `overflowing_add` isn't `Result<T>` and instead a tuple containing a boolean?
by hypeatei 4y ago
Slightly related, I wonder why the return type for `overflowing_add` isn't `Result<T>` and instead a tuple containing a boolean?
- re 4y agoThere are times when you want to know how much overflow occurred -- think of the way you learn to do multi-digit addition. There is a checked_add that returns an Option<T> if you only care about success/failure.
- sshine 4y agoAn example is efficient prime-field arithmetic: https://cp4space.hatsya.com/2021/09/01/an-efficient-prime-for-number-theoretic-transforms/ https://cp4space.hatsya.com/2021/09/01/an-efficient-prime-fo... > If A happened to be larger than C, and therefore the result of the subtraction underflowed, then we can correct for this by adding p to the result. [...] we can multiply B by 2^32 using a binary shift and a subtraction, and then add it to the result. We might encounter an overflow, but we can correct for that by subtracting p. (Highlighting the parts that relate to reacting to overflow.)
- jcparkyn 4y agoProbably because you'd want to access the value in either case, depending on your application.
- howinteresting 4y agoCould be a `Result<T, T>` which would seem to express the intent better.
- 3836293648 4y agoSometimes, sure. But an overflow doesn't have to be an error, it can be what you're after and you just want to know when it happens.
- howinteresting 4y agoBinary search is similar and the return type there is already Result<usize, usize>: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.binary_search https://doc.rust-lang.org/std/vec/struct.Vec.html#method.bin...
- sshine 4y agoMy guess is: The `(T, bool)` that gets returned is friendly towards optimization. If you don't use the bool, the overflowing arithmetic is reduced to efficient arithmetic which is overflowing by default. If you do use the bool, the generated code contains one extra instruction.