using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Brutal.Memory;
///
/// Provides the natural memory alignment requirement for an unmanaged type .
/// Serves as the C# equivalent of C++ alignof(T).
///
/// The unmanaged type whose alignment is to be queried.
public static unsafe class TypeAlign where T : unmanaged
{
///
/// Probe struct to measure padding added by the runtime between fields.
/// Explicitly sequential to prevent field reordering optimizations.
///
[StructLayout(LayoutKind.Sequential)]
private struct Probe
{
public byte Byte;
public T Value;
}
///
/// The natural alignment of type in bytes.
/// Guaranteed to be a power of two (1, 2, 4, 8, or 16).
///
public static readonly int Value = ComputeAlignment();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int ComputeAlignment()
{
Probe probe = default;
return (int)((byte*)&probe.Value - (byte*)&probe);
}
}