Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overflow on num::rational::Ratio #6

Open
cuviper opened this issue Dec 19, 2017 · 4 comments
Open

Overflow on num::rational::Ratio #6

cuviper opened this issue Dec 19, 2017 · 4 comments

Comments

@cuviper
Copy link
Member

cuviper commented Dec 19, 2017

From @rust-highfive on September 28, 2014 22:43

Issue by klutzy
Wednesday Aug 27, 2014 at 07:50 GMT

For earlier discussion, see rust-lang/rust#16782

This issue was labelled with: in the Rust repository


use std::i64::MIN;
use:num::rational::Ratio;

let a = Ratio::new(1, MIN);

Here a actually is -1 / MIN due to overflow in reduce():

        // keep denom positive!
        if self.denom < Zero::zero() {
            self.numer = -self.numer;
            self.denom = -self.denom;
        }

Copied from original issue: rust-num/num#12

@maxbla
Copy link
Contributor

maxbla commented Jun 27, 2019

We have some options regarding how to fix this.

  1. We could require that types used in a Ratio implement CheckedNeg. Ratio::new() would then return Option<Ratio>. I don't like this. It would mess up the API, and would be a breaking change.

  2. We could check after negating the denominator if it is still negative (negating a negative that can't be negated is a no-op in release mode). If it is, we could panic. It is better to panic early than give garbage results. I think in this scenario, it might make sense to add checked_new(T,T) -> Option<Ratio<T>>

  3. We could allow negative denominators. In this scenario, we would allow both numerator and denominator to be simultaneously negative. This would require additional logic all over the place, including in cmp(), hash() and reduce()

@maxbla maxbla mentioned this issue Mar 13, 2020
4 tasks
@vks
Copy link
Contributor

vks commented Feb 4, 2021

2 sounds like the best option for now.

@vks
Copy link
Contributor

vks commented Feb 10, 2021

At least in debug mode, this panics now. Can this be closed, or should it panic in release mode as well?

@inferiorhumanorgans
Copy link

It would be nice to implement 1, as an additional constructor (e.g. new_checked). I just ran into this while fuzzing a library and being able to get a Result back instead of catching a panic is a nice-to-have.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants