Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion library/core/src/num/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3954,7 +3954,20 @@ macro_rules! uint_impl {
#[must_use = "this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
let result = self.one_less_than_next_power_of_two().checked_add(1);

if let Some(result) = result {
// SAFETY: `one_less_than_next_power_of_two` returns one less than the
// smallest power of two greater than or equal to `self`. Therefore, if
// adding one succeeds, the result is a power of two at least as large as
// `self`.
unsafe {
crate::hint::assert_unchecked(result.is_power_of_two());
crate::hint::assert_unchecked(result >= self);
}
}

result
}

/// Returns the smallest power of two greater than or equal to `n`. If
Expand Down
25 changes: 25 additions & 0 deletions tests/codegen-llvm/checked-next-power-of-two.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//@ compile-flags: -Copt-level=3

#![crate_type = "lib"]
#![no_std]

// CHECK-LABEL: @checked_next_power_of_two_properties
// CHECK: ret i1 true
#[no_mangle]
pub fn checked_next_power_of_two_properties(value: u64) -> bool {
value
.checked_next_power_of_two()
.is_none_or(|result| result.is_power_of_two() && result >= value)
}

// CHECK-LABEL: @modulo_checked_next_power_of_two
// CHECK-NOT: udiv
// CHECK-NOT: urem
// CHECK: and i64
// CHECK-NOT: udiv
// CHECK-NOT: urem
// CHECK: ret
#[no_mangle]
pub fn modulo_checked_next_power_of_two(value: u64, dividend: u64) -> Option<u64> {
value.checked_next_power_of_two().map(|divisor| dividend % divisor)
}
Loading