next_multiple_of Rounds Sizes Up To Alignment
Round sizes up to alignment boundaries with next_multiple_of for buffers and pages, with a checked variant that returns None instead of panicking.
Code
fn allocate_frame(size: u64) -> u64 {
// 帧按 8 字节对齐分配:不足则向上取整到对齐边界
size.next_multiple_of(8)
}
fn main() {
let sizes = [1u64, 7, 8, 9, 64];
let aligned: Vec<u64> = sizes.iter().map(|&s| allocate_frame(s)).collect();
println!("sizes : {sizes:?}");
println!("aligned : {aligned:?}");
// 页对齐同理:4096
let page = 5000u64.next_multiple_of(4096);
println!("page for 5000 bytes: {page}");
// checked 变体:rhs 为 0 或溢出时给 None 而不是 panic
println!("checked by zero: {:?}", 7u64.checked_next_multiple_of(0));
}What the code does
Structurally, expect the functions allocate_frame and main and nothing else.
Applying it
Signature: fn allocate_frame(size: u64) -> u64
Running the file prints labeled results such as sizes :, aligned :, page for 5000 bytes: — each operation’s effect is visible in the output.
Treat main as the orchestrator calling allocate_frame in a fixed order.
Statements that matter
let aligned: Vec<u64> = sizes.iter().map(|&s| allocate_frame(s)).collect();
fn allocate_frame(size: u64) -> u64 {
// 帧按 8 字节对齐分配:不足则向上取整到对齐边界
size.next_multiple_of(8)
}
Interactive Tools for This Topic
FAQ
- What does next_multiple_of Rounds Sizes Up To Alignment print when run?
- The script runs standalone; its 4 labeled outputs include `sizes :`, `aligned :`, `page for 5000 bytes:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.