Skip to content

Commit a160258

Browse files
authored
Rollup merge of rust-lang#65092 - tspiteri:const-is-pow2, r=oli-obk
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
2 parents aba8489 + d689c70 commit a160258

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/libcore/num/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -3757,8 +3757,8 @@ assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
37573757
```"),
37583758
#[stable(feature = "rust1", since = "1.0.0")]
37593759
#[inline]
3760-
pub fn is_power_of_two(self) -> bool {
3761-
(self.wrapping_sub(1)) & self == 0 && !(self == 0)
3760+
pub const fn is_power_of_two(self) -> bool {
3761+
self.count_ones() == 1
37623762
}
37633763
}
37643764

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// run-pass
2+
3+
const IS_POWER_OF_TWO_A: bool = 0u32.is_power_of_two();
4+
const IS_POWER_OF_TWO_B: bool = 32u32.is_power_of_two();
5+
const IS_POWER_OF_TWO_C: bool = 33u32.is_power_of_two();
6+
7+
fn main() {
8+
assert!(!IS_POWER_OF_TWO_A);
9+
assert!(IS_POWER_OF_TWO_B);
10+
assert!(!IS_POWER_OF_TWO_C);
11+
}

0 commit comments

Comments
 (0)