next_power_of_two Rounds Capacity Up

next_power_of_two grows a request to the nearest power of two for table sizing, and checked_next_power_of_two reports None instead of wrapping.

RustData Integrity

Code

rustsnippet
16 lines
fn main() {
    let needed = 100usize;

    // 哈希表、环形缓冲常按 2 的幂分配:向上取到最近的幂
    let capacity = needed.next_power_of_two();
    println!("needed={needed} capacity={capacity}");

    // 已经是 2 的幂:保持不变,不会翻倍
    println!("already power: {}", 64usize.next_power_of_two());

    // checked 变体在装不下时返回 None,而不是回绕成错误的值
    println!("checked overflow: {:?}", (u32::MAX / 2 + 2).checked_next_power_of_two());

    // u32::MAX 的下一个幂是 2^32,u32 装不下:同样是 None
    println!("max checked: {:?}", u32::MAX.checked_next_power_of_two());
}

The shape of the program

Under the hood: the function main.

Caveats

  • Zero third-party dependencies: every API used comes from the runtime.

Applying it

The signature at the center: fn main()

The run tags its own steps: needed=, already power:, checked overflow:.

Statements that matter

let capacity = needed.next_power_of_two();
let needed = 100usize;

Interactive Tools for This Topic

FAQ

What does next_power_of_two Rounds Capacity Up print when run?
Invoke the file as-is — the `needed=`, `already power:`, `checked overflow:` prefixes identify which step printed each line.