Function align_offset

Source
pub const fn align_offset<T>(current_offset: u32) -> u32
Expand 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 alignment of type T, this function calculates the next aligned offset from current_offset.
  • It ensures that the result is a multiple of alignment by adding alignment - 1 to current_offset and then clearing the lower bits using bitwise AND with the negation of alignment - 1.
let alignment = mem::align_of::<T>() as u32;
(current_offset + alignment - 1) & !(alignment - 1)