using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Misaki.HighPerformance.Unsafe.Helpers; public static unsafe class MemoryUtilities { [StructLayout(LayoutKind.Sequential)] private struct AlignOfHelper where T : struct { public byte dummy; public T data; } /// /// Clears a block of memory by setting it to zero. It initializes a specified number of bytes at a given memory /// address. /// /// Specifies the memory address where the clearing operation will begin. /// Indicates the number of bytes to be cleared in the memory block. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void MemClear(void* ptr, nuint size) { NativeMemory.Clear(ptr, size); } /// /// Sets a block of memory to a specified byte value for a given size. /// /// The memory address where the byte value will be set. /// The number of bytes to set to the specified value. /// The byte value to which the memory block will be initialized. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void MemSet(void* ptr, nuint size, byte value) { NativeMemory.Fill(ptr, size, value); } /// /// Copies a block of memory from a source location to a destination location. /// /// Indicates the memory address from which data will be copied. /// Specifies the memory address where the copied data will be stored. /// Defines the number of bytes to be copied from the source to the destination. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void MemCpy(void* source, void* destination, nuint size) { NativeMemory.Copy(source, destination, size); } /// /// Calculates the size in bytes of a specified unmanaged type. /// /// Represents an unmanaged type for which the size is being calculated. /// Returns the size of the specified type as an unsigned integer. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nuint SizeOf() where T : unmanaged { return (nuint)sizeof(T); } /// /// Calculates the alignment size of a specified unmanaged type. /// /// Represents an unmanaged type for which the alignment size is being calculated. /// Returns the difference in size between a helper structure and the specified type. public static nuint AlignOf() where T : unmanaged { return (nuint)(sizeof(AlignOfHelper) - sizeof(T)); } /// /// Calculates the alignment size difference between a specified struct and a helper struct. /// /// Represents a value type that is used to determine the alignment size. /// Returns the size difference in bytes as an integer. public static int MarshalAlignOf() where T : struct { return Marshal.SizeOf>() - Marshal.SizeOf(); } }