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

i32::pow only handles overflow up to an exponent of 1023 #28012

Closed
jonas-schievink opened this issue Aug 26, 2015 · 5 comments
Closed

i32::pow only handles overflow up to an exponent of 1023 #28012

jonas-schievink opened this issue Aug 26, 2015 · 5 comments

Comments

@jonas-schievink
Copy link
Contributor

Playpen: http://is.gd/zhwksu

fn main() {
    let x: i32 = 2;

    println!("{}", x.pow(1024));
    println!("{}", x.pow(1023));
}

Prints:

0
thread '<main>' panicked at 'arithmetic operation overflowed', ../src/libcore/num/mod.rs:550

Interestingly, this only seems to happen with an even base. The overflow is detected correctly when x is set to 3 or other odd numbers.

@bluss
Copy link
Member

bluss commented Aug 26, 2015

cc @pnkfelix introducing this behavior in c8db89a, it may be deliberate.

@steveklabnik
Copy link
Member

/cc @rust-lang/libs @rust-lang/lang is this intended behavior?

@BurntSushi
Copy link
Member

I'm not sure this is intended behavior, and if it was, it does seem a little surprising. What seems to happen is if the exponent is even, and each iteration of the pow loop divides by 2, then the if (exp & 1) == 1 { check is never hit, which I think is supposed to cause pow to panic if overflow is observable. Certainly overflow is observable here.

@alexcrichton
Copy link
Member

This looks like a bug, seems fine to fix

@nikomatsakis
Copy link
Contributor

I agree with @alexcrichton

PeterReid added a commit to PeterReid/rust that referenced this issue Sep 5, 2015
Overflows in integer pow() computations would be missed if they
preceded a 0 bit of the exponent being processed. This made
calls such as 2i32.pow(1024) not trigger an overflow.
PeterReid added a commit to PeterReid/rust that referenced this issue Sep 14, 2015
This would catch regressions of issue rust-lang#28012.
bors added a commit that referenced this issue Sep 14, 2015
Overflows in integer pow() computations would be missed if they
preceded a 0 bit of the exponent being processed. This made
calls such as 2i32.pow(1024) not trigger an overflow.

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

No branches or pull requests

6 participants