Function alignPointer [src]
Aligns a given pointer value to a specified alignment factor.
Returns an aligned pointer or null if one of the following conditions is
met:
The aligned pointer would not fit the address space,
The delta required to align the pointer is not a multiple of the pointee's
type.
Prototype
pub fn alignPointer(ptr: anytype, align_to: usize) ?@TypeOf(ptr)
Parameters
align_to: usize
Example
test alignPointer {
const S = struct {
fn checkAlign(comptime T: type, base: usize, align_to: usize, expected: usize) !void {
const ptr: T = @ptrFromInt(base);
const aligned = alignPointer(ptr, align_to);
try testing.expectEqual(expected, @intFromPtr(aligned));
}
};
try S.checkAlign([*]u8, 0x123, 0x200, 0x200);
try S.checkAlign([*]align(4) u8, 0x10, 2, 0x10);
try S.checkAlign([*]u32, 0x10, 2, 0x10);
try S.checkAlign([*]u32, 0x4, 16, 0x10);
// Misaligned.
try S.checkAlign([*]align(1) u32, 0x3, 2, 0);
// Overflow.
try S.checkAlign([*]u32, math.maxInt(usize) - 3, 8, 0);
}
Source
pub fn alignPointer(ptr: anytype, align_to: usize) ?@TypeOf(ptr) {
const adjust_off = alignPointerOffset(ptr, align_to) orelse return null;
// Avoid the use of ptrFromInt to avoid losing the pointer provenance info.
return @alignCast(ptr + adjust_off);
}