StitchATon2/Infra/Buffers/MemoryAllocator.cs

36 lines
1.4 KiB
C#
Raw Normal View History

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