2025-07-30 07:30:00 +07:00
|
|
|
using System.Buffers;
|
2025-07-31 07:40:28 +07:00
|
|
|
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
|
2025-08-01 22:13:13 +07:00
|
|
|
=> 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
|
|
|
|
2025-07-31 07:40:28 +07:00
|
|
|
public static unsafe IBuffer<T> Clone<T>(this IBuffer<T> buffer) where T : unmanaged
|
|
|
|
|
{
|
2025-08-01 22:13:13 +07:00
|
|
|
if (buffer is not ImmovableMemory<T> unmanagedMemory)
|
|
|
|
|
throw new NotSupportedException();
|
2025-07-31 07:40:28 +07:00
|
|
|
|
2025-08-01 22:13:13 +07:00
|
|
|
var newBuffer = new ImmovableMemory<T>(buffer.Length);
|
|
|
|
|
var byteCount = (uint)(Unsafe.SizeOf<T>() * buffer.Length);
|
|
|
|
|
Unsafe.CopyBlock(newBuffer.Pointer, unmanagedMemory.Pointer, byteCount);
|
|
|
|
|
return newBuffer;
|
2025-07-31 07:40:28 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static unsafe void Copy<T>(this IBuffer<T> source, IBuffer<T> destination, int count) where T : unmanaged
|
|
|
|
|
{
|
2025-08-01 22:13:13 +07:00
|
|
|
if (source is not ImmovableMemory<T> sourceBuffer || destination is not ImmovableMemory<T> destinationBuffer)
|
|
|
|
|
throw new NotSupportedException();
|
2025-07-31 07:40:28 +07:00
|
|
|
|
2025-08-01 22:13:13 +07:00
|
|
|
var byteCount = (uint)(Unsafe.SizeOf<T>() * count);
|
|
|
|
|
Unsafe.CopyBlock(destinationBuffer.Pointer, sourceBuffer.Pointer, byteCount);
|
2025-07-31 07:40:28 +07:00
|
|
|
}
|
2025-07-30 07:30:00 +07:00
|
|
|
}
|