Skip to content

Instantly share code, notes, and snippets.

@ctreffs
Last active February 5, 2021 23:01
Show Gist options
  • Save ctreffs/1cf72cd0d5e23d77fe55a011ea01a153 to your computer and use it in GitHub Desktop.
Save ctreffs/1cf72cd0d5e23d77fe55a011ea01a153 to your computer and use it in GitHub Desktop.
Metal buffer size alignment calculation
/// In Metal buffers (MTLBuffer) require a specific alignment, this function helps with that.
/// <https://developer.apple.com/documentation/metal/mtlcomputecommandencoder/2928169-setbuffers#discussion>
public func align<I>(_ value: I, to alignment: I) -> I where I: BinaryInteger {
assert(alignment == 0 || (alignment & (alignment-1)) == 0, "Alignment must be 0 or power of 2")
if alignment == 0 {
return value
} else if (value & (alignment - 1)) == 0 {
return value
} else {
return (value + alignment) & ~(alignment-1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment