WorkBufferAllocator.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Ryujinx.Audio.Renderer.Utils;
  2. using Ryujinx.Common;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Runtime.CompilerServices;
  6. namespace Ryujinx.Audio.Renderer.Common
  7. {
  8. public class WorkBufferAllocator
  9. {
  10. public Memory<byte> BackingMemory { get; }
  11. public ulong Offset { get; private set; }
  12. public WorkBufferAllocator(Memory<byte> backingMemory)
  13. {
  14. BackingMemory = backingMemory;
  15. }
  16. public Memory<byte> Allocate(ulong size, int align)
  17. {
  18. Debug.Assert(align != 0);
  19. if (size != 0)
  20. {
  21. ulong alignedOffset = BitUtils.AlignUp<ulong>(Offset, (ulong)align);
  22. if (alignedOffset + size <= (ulong)BackingMemory.Length)
  23. {
  24. Memory<byte> result = BackingMemory.Slice((int)alignedOffset, (int)size);
  25. Offset = alignedOffset + size;
  26. // Clear the memory to be sure that is does not contain any garbage.
  27. result.Span.Fill(0);
  28. return result;
  29. }
  30. }
  31. return Memory<byte>.Empty;
  32. }
  33. public Memory<T> Allocate<T>(ulong count, int align) where T : unmanaged
  34. {
  35. Memory<byte> allocatedMemory = Allocate((ulong)Unsafe.SizeOf<T>() * count, align);
  36. if (allocatedMemory.IsEmpty)
  37. {
  38. return Memory<T>.Empty;
  39. }
  40. return SpanMemoryManager<T>.Cast(allocatedMemory);
  41. }
  42. public static ulong GetTargetSize<T>(ulong currentSize, ulong count, int align) where T : unmanaged
  43. {
  44. return BitUtils.AlignUp<ulong>(currentSize, (ulong)align) + (ulong)Unsafe.SizeOf<T>() * count;
  45. }
  46. }
  47. }