mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 13:08:24 +01:00
Add NativeStackAllocator with scoped RAII and TypeAlign helper
Signed-off-by: SashaGonch228 <sashaandsergey20@gmail.com>
This commit is contained in:
parent
a25cdf80b2
commit
960d624b32
1 changed files with 145 additions and 0 deletions
36
Brutal.Memory/TypeAlign.cs
Normal file
36
Brutal.Memory/TypeAlign.cs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.Memory;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the natural memory alignment requirement for an unmanaged type <typeparamref name="T"/>.
|
||||
/// Serves as the C# equivalent of C++ <c>alignof(T)</c>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The unmanaged type whose alignment is to be queried.</typeparam>
|
||||
public static unsafe class TypeAlign<T> where T : unmanaged
|
||||
{
|
||||
/// <summary>
|
||||
/// Probe struct to measure padding added by the runtime between fields.
|
||||
/// Explicitly sequential to prevent field reordering optimizations.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Probe
|
||||
{
|
||||
public byte Byte;
|
||||
public T Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The natural alignment of type <typeparamref name="T"/> in bytes.
|
||||
/// Guaranteed to be a power of two (1, 2, 4, 8, or 16).
|
||||
/// </summary>
|
||||
public static readonly int Value = ComputeAlignment();
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static int ComputeAlignment()
|
||||
{
|
||||
Probe probe = default;
|
||||
return (int)((byte*)&probe.Value - (byte*)&probe);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue