Function alignPointerOffset [src]
Returns the number of elements that, if added to the given pointer, align it
to a multiple of the given quantity, 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 alignPointerOffset(ptr: anytype, align_to: usize) ?usize
Parameters
align_to: usize
Source
pub fn alignPointerOffset(ptr: anytype, align_to: usize) ?usize {
assert(isValidAlign(align_to));
const T = @TypeOf(ptr);
const info = @typeInfo(T);
if (info != .pointer or info.pointer.size != .many)
@compileError("expected many item pointer, got " ++ @typeName(T));
// Do nothing if the pointer is already well-aligned.
if (align_to <= info.pointer.alignment)
return 0;
// Calculate the aligned base address with an eye out for overflow.
const addr = @intFromPtr(ptr);
var ov = @addWithOverflow(addr, align_to - 1);
if (ov[1] != 0) return null;
ov[0] &= ~@as(usize, align_to - 1);
// The delta is expressed in terms of bytes, turn it into a number of child
// type elements.
const delta = ov[0] - addr;
const pointee_size = @sizeOf(info.pointer.child);
if (delta % pointee_size != 0) return null;
return delta / pointee_size;
}