num-rational icon indicating copy to clipboard operation
num-rational copied to clipboard

Stackoverflow with PartialEq and PartialOrd

Open redweasel opened this issue 4 months ago • 0 comments

The following code produces a stackoverflow, which kills the process.

use num_rational::*; // 0.4.2
use num_bigint::*; // 0.4.6
use num_traits::One;

fn main() {
    let mut a = BigRational::new("29".parse().unwrap(), "28".parse().unwrap());
    for _ in 0..13 {
        a = &a * &a;
    }
    let b = Ratio::new_raw(a.numer() + &BigInt::one(), a.denom() + &BigInt::one());
    assert!(a > b);
    assert!(a != b);
}

If anyone uses this on a server where the numbers can be user supplied, this would lead to a DoS, so this is security critical. The fix is to write the continued fractions algorithm for the comparison in an iterative instead of a recursive way.

redweasel avatar Aug 19 '25 13:08 redweasel