using System.Buffers; using System.Runtime.CompilerServices; namespace StitchATon2.Infra.Buffers; public static class MemoryAllocator { public static IBuffer Allocate(int count) where T : unmanaged => new ImmovableMemory(count); public static IMemoryOwner AllocateManaged(int count) => MemoryPool.Shared.Rent(count); public static ArrayOwner AllocateArray(int count) where T : unmanaged => new(ArrayPool.Shared, count); public static unsafe IBuffer Clone(this IBuffer buffer) where T : unmanaged { if (buffer is not ImmovableMemory unmanagedMemory) throw new NotSupportedException(); var newBuffer = new ImmovableMemory(buffer.Length); var byteCount = (uint)(Unsafe.SizeOf() * buffer.Length); Unsafe.CopyBlock(newBuffer.Pointer, unmanagedMemory.Pointer, byteCount); return newBuffer; } public static unsafe void Copy(this IBuffer source, IBuffer destination, int count) where T : unmanaged { if (source is not ImmovableMemory sourceBuffer || destination is not ImmovableMemory destinationBuffer) throw new NotSupportedException(); var byteCount = (uint)(Unsafe.SizeOf() * count); Unsafe.CopyBlock(destinationBuffer.Pointer, sourceBuffer.Pointer, byteCount); } }