using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace ComputeSharp.Core.Helpers { /// /// A with helper methods to work with alignment and padding. /// internal static class AlignmentHelper { /// /// Pads the input size so that its pitch is aligned to a multiple of a specified length. /// /// The input size to pad, if needed. /// The target alignment. /// The padded value relative to the given inputs. [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Pad(int size, int alignment) { return (size + alignment - 1) & ~(alignment - 1); } /// /// Aligns a given offset to a specified boundary, if a given size increment would have crossed it. /// /// The starting offset to align, if needed. /// The size increment to apply to . /// The alignment boundary to calculate the final offset. /// A valid starting offset for the specified alignment. [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int AlignToBoundary(int offset, int size, int alignment) { if ((uint)offset / (uint)alignment == (uint)(offset + size - 1) / (uint)alignment) { return offset; } return (offset + alignment - 1) & ~(alignment - 1); } } }