Skip to content

Commit

Permalink
Rollup merge of rust-lang#65092 - tspiteri:const-is-pow2, r=oli-obk
Browse files Browse the repository at this point in the history
make is_power_of_two a const function

This makes `is_power_of_two` a const function by using `&` instead of short-circuiting `&&`; Rust supports bitwise `&` for `bool` and short-circuiting is not required in the existing expression.

I don't think this needs a const-hack label as I don't find the changed code less readable, if anything I prefer that it is clearer that short circuiting is not used.

@oli-obk
  • Loading branch information
Centril authored Oct 21, 2019
2 parents aba8489 + d689c70 commit a160258
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/libcore/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3757,8 +3757,8 @@ assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
```"),
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_power_of_two(self) -> bool {
(self.wrapping_sub(1)) & self == 0 && !(self == 0)
pub const fn is_power_of_two(self) -> bool {
self.count_ones() == 1
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/test/ui/consts/const-int-pow-rpass.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// run-pass

const IS_POWER_OF_TWO_A: bool = 0u32.is_power_of_two();
const IS_POWER_OF_TWO_B: bool = 32u32.is_power_of_two();
const IS_POWER_OF_TWO_C: bool = 33u32.is_power_of_two();

fn main() {
assert!(!IS_POWER_OF_TWO_A);
assert!(IS_POWER_OF_TWO_B);
assert!(!IS_POWER_OF_TWO_C);
}

0 comments on commit a160258

Please sign in to comment.