MemoryAllocator.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using Ryujinx.Common.Memory;
  2. using System;
  3. using System.Runtime.CompilerServices;
  4. using System.Runtime.InteropServices;
  5. namespace Ryujinx.Graphics.Nvdec.Vp9.Common
  6. {
  7. internal class MemoryAllocator : IDisposable
  8. {
  9. private const int PoolEntries = 10;
  10. private struct PoolItem
  11. {
  12. public IntPtr Pointer;
  13. public int Length;
  14. public bool InUse;
  15. }
  16. private PoolItem[] _pool = new PoolItem[PoolEntries];
  17. public ArrayPtr<T> Allocate<T>(int length) where T : unmanaged
  18. {
  19. int lengthInBytes = Unsafe.SizeOf<T>() * length;
  20. IntPtr ptr = IntPtr.Zero;
  21. for (int i = 0; i < PoolEntries; i++)
  22. {
  23. ref PoolItem item = ref _pool[i];
  24. if (!item.InUse && item.Length == lengthInBytes)
  25. {
  26. item.InUse = true;
  27. ptr = item.Pointer;
  28. break;
  29. }
  30. }
  31. if (ptr == IntPtr.Zero)
  32. {
  33. ptr = Marshal.AllocHGlobal(lengthInBytes);
  34. for (int i = 0; i < PoolEntries; i++)
  35. {
  36. ref PoolItem item = ref _pool[i];
  37. if (!item.InUse)
  38. {
  39. item.InUse = true;
  40. if (item.Pointer != IntPtr.Zero)
  41. {
  42. Marshal.FreeHGlobal(item.Pointer);
  43. }
  44. item.Pointer = ptr;
  45. item.Length = lengthInBytes;
  46. break;
  47. }
  48. }
  49. }
  50. return new ArrayPtr<T>(ptr, length);
  51. }
  52. public unsafe void Free<T>(ArrayPtr<T> arr) where T : unmanaged
  53. {
  54. IntPtr ptr = (IntPtr)arr.ToPointer();
  55. for (int i = 0; i < PoolEntries; i++)
  56. {
  57. ref PoolItem item = ref _pool[i];
  58. if (item.Pointer == ptr)
  59. {
  60. item.InUse = false;
  61. break;
  62. }
  63. }
  64. }
  65. public void Dispose()
  66. {
  67. for (int i = 0; i < PoolEntries; i++)
  68. {
  69. ref PoolItem item = ref _pool[i];
  70. if (item.Pointer != IntPtr.Zero)
  71. {
  72. Marshal.FreeHGlobal(item.Pointer);
  73. item.Pointer = IntPtr.Zero;
  74. }
  75. }
  76. }
  77. }
  78. }