pub const fn align_offset<T>(current_offset: u32) -> u32Expand description
Calculates the aligned offset for a given type T starting from current_offset.
This function aligns the given current_offset to the next boundary that satisfies the alignment requirements of type T.
§Parameters
current_offset: The initial offset that needs to be aligned.
§Returns
The aligned offset that is the next multiple of the alignment requirement of type T.
§Examples
ⓘ
use std::mem;
#[repr(C, align(8))]
struct Meta {
a: u64,
b: u64,
}
let initial_offset: u32 = 1;
let aligned_offset = align_offset::<Meta>(initial_offset);
assert_eq!(aligned_offset, 8);§Explanation
- Given an
alignmentof typeT, this function calculates the next aligned offset fromcurrent_offset. - It ensures that the result is a multiple of
alignmentby addingalignment - 1tocurrent_offsetand then clearing the lower bits using bitwise AND with the negation ofalignment - 1.
ⓘ
let alignment = mem::align_of::<T>() as u32;
(current_offset + alignment - 1) & !(alignment - 1)