← 中文资源

简体中文版本

next_power_of_two 容量向上取幂

next_power_of_two 把请求量取到最近的 2 的幂,已是幂次时保持不变;checked_next_power_of_two 在装不下时返回 None 而不是回绕。

阅读英文原文

实现说明

next_power_of_two 容量向上取幂以函数 main为骨架。

使用要点

  • 每一步打印都带着自己的标签:needed=、already power:、checked overflow:。

常见问题

运行「next_power_of_two 容量向上取幂」会打印什么?

整个文件跑完,输出行以 needed=、already power:、checked overflow: 这类前缀开头。

核心语句

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

代码示例

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());
}