Skip to content

Commit cbd84ae

Browse files
authored
Auto merge of #34942 - porglezomp:master, r=sfackler
Fix overflow checking in unsigned pow() The pow() method for unsigned integers produced 0 instead of trapping overflow for certain inputs. Calls such as 2u32.pow(1024) produced 0 when they should trap an overflow. This also adds tests for the correctly handling overflow in unsigned pow(). This was previously fixed for signed integers in #28248, but it seems unsigned integers got missed that time. For issue number #34913
2 parents e054701 + b8c4e9c commit cbd84ae

File tree

3 files changed

+27
-15
lines changed

3 files changed

+27
-15
lines changed

src/libcore/num/mod.rs

+11-15
Original file line numberDiff line numberDiff line change
@@ -2211,25 +2211,21 @@ macro_rules! uint_impl {
22112211
let mut base = self;
22122212
let mut acc = 1;
22132213

2214-
let mut prev_base = self;
2215-
let mut base_oflo = false;
2216-
while exp > 0 {
2214+
while exp > 1 {
22172215
if (exp & 1) == 1 {
2218-
if base_oflo {
2219-
// ensure overflow occurs in the same manner it
2220-
// would have otherwise (i.e. signal any exception
2221-
// it would have otherwise).
2222-
acc = acc * (prev_base * prev_base);
2223-
} else {
2224-
acc = acc * base;
2225-
}
2216+
acc = acc * base;
22262217
}
2227-
prev_base = base;
2228-
let (new_base, new_base_oflo) = base.overflowing_mul(base);
2229-
base = new_base;
2230-
base_oflo = new_base_oflo;
22312218
exp /= 2;
2219+
base = base * base;
22322220
}
2221+
2222+
// Deal with the final bit of the exponent separately, since
2223+
// squaring the base afterwards is not necessary and may cause a
2224+
// needless overflow.
2225+
if exp == 1 {
2226+
acc = acc * base;
2227+
}
2228+
22332229
acc
22342230
}
22352231

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// error-pattern:thread 'main' panicked at 'attempt to multiply with overflow'
12+
// compile-flags: -C debug-assertions
13+
14+
fn main() {
15+
let _x = 2u32.pow(1024);
16+
}

0 commit comments

Comments
 (0)