Rollup merge of #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
This commit is contained in:
commit
a160258927
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
11
src/test/ui/consts/const-int-pow-rpass.rs
Normal file
11
src/test/ui/consts/const-int-pow-rpass.rs
Normal file
@ -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);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user