Skip to content

Commit 9926b33

Browse files
committed
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(). For issue number #34913
1 parent ddf92ff commit 9926b33

File tree

3 files changed

+27
-15
lines changed

3 files changed

+27
-15
lines changed

src/libcore/num/mod.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2217,25 +2217,21 @@ macro_rules! uint_impl {
22172217
let mut base = self;
22182218
let mut acc = 1;
22192219

2220-
let mut prev_base = self;
2221-
let mut base_oflo = false;
2222-
while exp > 0 {
2220+
while exp > 1 {
22232221
if (exp & 1) == 1 {
2224-
if base_oflo {
2225-
// ensure overflow occurs in the same manner it
2226-
// would have otherwise (i.e. signal any exception
2227-
// it would have otherwise).
2228-
acc = acc * (prev_base * prev_base);
2229-
} else {
2230-
acc = acc * base;
2231-
}
2222+
acc = acc * base;
22322223
}
2233-
prev_base = base;
2234-
let (new_base, new_base_oflo) = base.overflowing_mul(base);
2235-
base = new_base;
2236-
base_oflo = new_base_oflo;
22372224
exp /= 2;
2225+
base = base * base;
22382226
}
2227+
2228+
// Deal with the final bit of the exponent separately, since
2229+
// squaring the base afterwards is not necessary and may cause a
2230+
// needless overflow.
2231+
if exp == 1 {
2232+
acc = acc * base;
2233+
}
2234+
22392235
acc
22402236
}
22412237

Lines changed: 16 additions & 0 deletions
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 'attempted 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)